Compare commits

..

3 Commits
swift6 ... xpc

Author SHA1 Message Date
93b51f9e9b Dump 2022-02-16 22:02:57 -08:00
ba1c4c1563 XPC to agent working 2022-02-11 23:31:03 -08:00
b41c036ea0 Not working because xpc service 2022-02-11 22:52:45 -08:00
97 changed files with 2452 additions and 7323 deletions

Binary file not shown.

Before

Width:  |  Height:  |  Size: 572 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 545 KiB

BIN
.github/readme/app.png vendored Normal file

Binary file not shown.

After

Width:  |  Height:  |  Size: 456 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 1.3 MiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 162 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 1.7 MiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 1.0 MiB

After

Width:  |  Height:  |  Size: 1.1 MiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 259 KiB

After

Width:  |  Height:  |  Size: 190 KiB

View File

@ -1,16 +0,0 @@
name: Add bugs to bugs project
on:
issues:
types:
- opened
jobs:
add-to-project:
name: Add issue to project
runs-on: ubuntu-latest
steps:
- uses: actions/add-to-project@v1.0.1
with:
project-url: https://github.com/users/maxgoedjen/projects/1
github-token: ${{ secrets.ADD_TO_PROJECT_PAT }}

View File

@ -5,11 +5,10 @@ on:
- cron: "0 8 * * *" - cron: "0 8 * * *"
jobs: jobs:
build: build:
# runs-on: macOS-latest runs-on: macos-11.0
runs-on: macos-15
timeout-minutes: 10 timeout-minutes: 10
steps: steps:
- uses: actions/checkout@v4 - uses: actions/checkout@v2
- name: Setup Signing - name: Setup Signing
env: env:
SIGNING_DATA: ${{ secrets.SIGNING_DATA }} SIGNING_DATA: ${{ secrets.SIGNING_DATA }}
@ -20,7 +19,7 @@ jobs:
APPLE_API_KEY_ID: ${{ secrets.APPLE_API_KEY_ID }} APPLE_API_KEY_ID: ${{ secrets.APPLE_API_KEY_ID }}
run: ./.github/scripts/signing.sh run: ./.github/scripts/signing.sh
- name: Set Environment - name: Set Environment
run: sudo xcrun xcode-select -s /Applications/Xcode_16.2.app run: sudo xcrun xcode-select -s /Applications/Xcode_13.2.1.app
- name: Update Build Number - name: Update Build Number
env: env:
RUN_ID: ${{ github.run_id }} RUN_ID: ${{ github.run_id }}
@ -41,14 +40,10 @@ jobs:
run: xcrun notarytool submit --key ~/.private_keys/AuthKey_$APPLE_API_KEY_ID.p8 --key-id $APPLE_API_KEY_ID --issuer $APPLE_API_ISSUER Secretive.zip run: xcrun notarytool submit --key ~/.private_keys/AuthKey_$APPLE_API_KEY_ID.p8 --key-id $APPLE_API_KEY_ID --issuer $APPLE_API_ISSUER Secretive.zip
- name: Document SHAs - name: Document SHAs
run: | run: |
echo "sha-512:"
shasum -a 512 Secretive.zip shasum -a 512 Secretive.zip
shasum -a 512 Archive.zip shasum -a 512 Archive.zip
echo "sha-256:"
shasum -a 256 Secretive.zip
shasum -a 256 Archive.zip
- name: Upload App to Artifacts - name: Upload App to Artifacts
uses: actions/upload-artifact@v4 uses: actions/upload-artifact@v1
with: with:
name: Secretive.zip name: Secretive.zip
path: Secretive.zip path: Secretive.zip

View File

@ -6,11 +6,10 @@ on:
- '*' - '*'
jobs: jobs:
test: test:
# runs-on: macOS-latest runs-on: macos-11.0
runs-on: macos-15
timeout-minutes: 10 timeout-minutes: 10
steps: steps:
- uses: actions/checkout@v4 - uses: actions/checkout@v1
- name: Setup Signing - name: Setup Signing
env: env:
SIGNING_DATA: ${{ secrets.SIGNING_DATA }} SIGNING_DATA: ${{ secrets.SIGNING_DATA }}
@ -21,18 +20,17 @@ jobs:
APPLE_API_KEY_ID: ${{ secrets.APPLE_API_KEY_ID }} APPLE_API_KEY_ID: ${{ secrets.APPLE_API_KEY_ID }}
run: ./.github/scripts/signing.sh run: ./.github/scripts/signing.sh
- name: Set Environment - name: Set Environment
run: sudo xcrun xcode-select -s /Applications/Xcode_16.2.app run: sudo xcrun xcode-select -s /Applications/Xcode_13.2.1.app
- name: Test - name: Test
run: | run: |
pushd Sources/Packages pushd Sources/Packages
swift test swift test
popd popd
build: build:
# runs-on: macOS-latest runs-on: macos-11.0
runs-on: macos-15
timeout-minutes: 10 timeout-minutes: 10
steps: steps:
- uses: actions/checkout@v4 - uses: actions/checkout@v2
- name: Setup Signing - name: Setup Signing
env: env:
SIGNING_DATA: ${{ secrets.SIGNING_DATA }} SIGNING_DATA: ${{ secrets.SIGNING_DATA }}
@ -43,7 +41,7 @@ jobs:
APPLE_API_KEY_ID: ${{ secrets.APPLE_API_KEY_ID }} APPLE_API_KEY_ID: ${{ secrets.APPLE_API_KEY_ID }}
run: ./.github/scripts/signing.sh run: ./.github/scripts/signing.sh
- name: Set Environment - name: Set Environment
run: sudo xcrun xcode-select -s /Applications/Xcode_16.2.app run: sudo xcrun xcode-select -s /Applications/Xcode_13.2.1.app
- name: Update Build Number - name: Update Build Number
env: env:
TAG_NAME: ${{ github.ref }} TAG_NAME: ${{ github.ref }}
@ -66,12 +64,8 @@ jobs:
run: xcrun notarytool submit --key ~/.private_keys/AuthKey_$APPLE_API_KEY_ID.p8 --key-id $APPLE_API_KEY_ID --issuer $APPLE_API_ISSUER Secretive.zip run: xcrun notarytool submit --key ~/.private_keys/AuthKey_$APPLE_API_KEY_ID.p8 --key-id $APPLE_API_KEY_ID --issuer $APPLE_API_ISSUER Secretive.zip
- name: Document SHAs - name: Document SHAs
run: | run: |
echo "sha-512:"
shasum -a 512 Secretive.zip shasum -a 512 Secretive.zip
shasum -a 512 Archive.zip shasum -a 512 Archive.zip
echo "sha-256:"
shasum -a 256 Secretive.zip
shasum -a 256 Archive.zip
- name: Create Release - name: Create Release
id: create_release id: create_release
uses: actions/create-release@v1 uses: actions/create-release@v1
@ -107,12 +101,12 @@ jobs:
asset_name: Secretive.zip asset_name: Secretive.zip
asset_content_type: application/zip asset_content_type: application/zip
- name: Upload App to Artifacts - name: Upload App to Artifacts
uses: actions/upload-artifact@v4 uses: actions/upload-artifact@v1
with: with:
name: Secretive.zip name: Secretive.zip
path: Secretive.zip path: Secretive.zip
- name: Upload Archive to Artifacts - name: Upload Archive to Artifacts
uses: actions/upload-artifact@v4 uses: actions/upload-artifact@v1
with: with:
name: Xcode_Archive.zip name: Xcode_Archive.zip
path: Archive.zip path: Archive.zip

View File

@ -3,13 +3,12 @@ name: Test
on: [push, pull_request] on: [push, pull_request]
jobs: jobs:
test: test:
# runs-on: macOS-latest runs-on: macos-11.0
runs-on: macos-15
timeout-minutes: 10 timeout-minutes: 10
steps: steps:
- uses: actions/checkout@v4 - uses: actions/checkout@v2
- name: Set Environment - name: Set Environment
run: sudo xcrun xcode-select -s /Applications/Xcode_16.2.app run: sudo xcrun xcode-select -s /Applications/Xcode_13.2.1.app
- name: Test - name: Test
run: | run: |
pushd Sources/Packages pushd Sources/Packages

View File

@ -26,15 +26,6 @@ Host *
IdentityAgent /Users/$YOUR_USERNAME/Library/Containers/com.maxgoedjen.Secretive.SecretAgent/Data/socket.ssh IdentityAgent /Users/$YOUR_USERNAME/Library/Containers/com.maxgoedjen.Secretive.SecretAgent/Data/socket.ssh
``` ```
## nushell
Add this to your `~/.ssh/config` (the path should match the socket path from the setup flow).
```
Host *
IdentityAgent /Users/$YOUR_USERNAME/Library/Containers/com.maxgoedjen.Secretive.SecretAgent/Data/socket.ssh
```
## Cyberduck ## Cyberduck
Add this to `~/Library/LaunchAgents/com.maxgoedjen.Secretive.SecretAgent.plist` Add this to `~/Library/LaunchAgents/com.maxgoedjen.Secretive.SecretAgent.plist`
@ -60,31 +51,6 @@ Add this to `~/Library/LaunchAgents/com.maxgoedjen.Secretive.SecretAgent.plist`
Log out and log in again before launching Cyberduck. Log out and log in again before launching Cyberduck.
## Mountain Duck
Add this to `~/Library/LaunchAgents/com.maxgoedjen.Secretive.SecretAgent.plist`
```
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd">
<plist version="1.0">
<dict>
<key>Label</key>
<string>link-ssh-auth-sock</string>
<key>ProgramArguments</key>
<array>
<string>/bin/sh</string>
<string>-c</string>
<string>/bin/ln -sf $HOME/Library/Containers/com.maxgoedjen.Secretive.SecretAgent/Data/socket.ssh $SSH_AUTH_SOCK</string>
</array>
<key>RunAtLoad</key>
<true/>
</dict>
</plist>
```
Log out and log in again before launching Mountain Duck.
## GitKraken ## GitKraken
Add this to `~/Library/LaunchAgents/com.maxgoedjen.Secretive.SecretAgent.plist` Add this to `~/Library/LaunchAgents/com.maxgoedjen.Secretive.SecretAgent.plist`

View File

@ -14,10 +14,6 @@ Secretive is designed to be easily auditable by people who are considering using
All contributors must abide by the [Code of Conduct](CODE_OF_CONDUCT.md) All contributors must abide by the [Code of Conduct](CODE_OF_CONDUCT.md)
## Localization
If you'd like to contribute a translation, please see [Localizing](LOCALIZING.md) to get started.
## Credits ## Credits
If you make a material contribution to the app, please add yourself to the end of the [credits](https://github.com/maxgoedjen/secretive/blob/main/Secretive/Credits.rtf). If you make a material contribution to the app, please add yourself to the end of the [credits](https://github.com/maxgoedjen/secretive/blob/main/Secretive/Credits.rtf).

14
FAQ.md
View File

@ -12,10 +12,6 @@ Secretive relies on the `SSH_AUTH_SOCK` environment variable being respected. Th
Please run `ssh -Tv git@github.com` in your terminal and paste the output in a [new GitHub issue](https://github.com/maxgoedjen/secretive/issues/new) with a description of your issue. Please run `ssh -Tv git@github.com` in your terminal and paste the output in a [new GitHub issue](https://github.com/maxgoedjen/secretive/issues/new) with a description of your issue.
### Secretive was working for me, but now it has stopped
Try running the "Setup Secretive" process by clicking on "Help", then "Setup Secretive." If that doesn't work, follow the process above.
### Secretive prompts me to type my password instead of using my Apple Watch ### Secretive prompts me to type my password instead of using my Apple Watch
1) Make sure you have enabled "Use your Apple Watch to unlock apps and your Mac" in System Preferences --> Security & Privacy: 1) Make sure you have enabled "Use your Apple Watch to unlock apps and your Mac" in System Preferences --> Security & Privacy:
@ -30,15 +26,7 @@ Try running the "Setup Secretive" process by clicking on "Help", then "Setup Sec
### How do I tell SSH to use a specific key? ### How do I tell SSH to use a specific key?
Beginning with Secretive 2.2, every secret has an automatically generated public key file representation on disk, and the path to it is listed under "Public Key Path" in Secretive. You can specify that you want to use that key in your `~/.ssh/config`. [This ServerFault answer](https://serverfault.com/a/295771) has more details on setting that up. You can create a `mykey.pub` (where `mykey` is the name of your key) in your `~/.ssh/` directory with the contents of your public key, and specify that you want to use that key in your `~/.ssh/config`. [This ServerFault answer](https://serverfault.com/a/295771) has more details on setting that up
### How can I generate an RSA key?
The Mac's Secure Enclave only supports 256-bit EC keys, so inherently Secretive cannot support generating RSA keys.
### Can I use Secretive for SSH Agent Forwarding?
Yes, you can! Once you've set up Secretive, just add `ForwardAgent yes` to the hosts you want to forward to in your SSH config file. Afterwards, any use of one of your SSH keys on the remote host must be authenticated through Secretive.
### Why should I trust you? ### Why should I trust you?

View File

@ -1,37 +0,0 @@
# Localizing Secretive
If you speak another language, and would like to help translate Secretive to support that language, we'd love your help!
## Getting Started
### Download Xcode
Download the latest version of Xcode (at minimum, Xcode 15) from [Apple](http://developer.apple.com/download/applications/).
### Clone Secretive
Clone Secretive using [these instructions from GitHub](https://docs.github.com/en/repositories/creating-and-managing-repositories/cloning-a-repository).
### Open Secretive
Open [Sources/Secretive.xcodeproj](Sources/Secretive.xcodeproj) in Xcode.
### Translate
Navigate to [Secretive/Localizable](Sources/Secretive/Localizable.xcstrings).
<img src="/.github/readme/localize_sidebar.png" alt="Screenshot of Xcode navigating to the Localizable file" width="300">
If your language already has an in-progress localization, select it from the list. If it isn't there, hit the "+" button and choose your language from the list.
<img src="/.github/readme/localize_add.png" alt="Screenshot of Xcode adding a new language" width="600">
Start translating! You'll see a list of english phrases, and a space to add a translation of your language.
### Create a Pull Request
Push your changes and open a pull request.
### Questions
Please open an issue if you have a question about translating the app. I'm more than happy to clarify any terms that are ambiguous or confusing. Thanks for contributing!

View File

@ -3,10 +3,7 @@
Secretive is an app for storing and managing SSH keys in the Secure Enclave. It is inspired by the [sekey project](https://github.com/sekey/sekey), but rewritten in Swift with no external dependencies and with a handy native management app. Secretive is an app for storing and managing SSH keys in the Secure Enclave. It is inspired by the [sekey project](https://github.com/sekey/sekey), but rewritten in Swift with no external dependencies and with a handy native management app.
<picture> <img src="/.github/readme/app.png" alt="Screenshot of Secretive" width="600">
<source media="(prefers-color-scheme: dark)" srcset="/.github/readme/app-dark.png">
<img src="/.github/readme/app-light.png" alt="Screenshot of Secretive" width="600">
</picture>
## Why? ## Why?
@ -17,15 +14,15 @@ The most common setup for SSH keys is just keeping them on disk, guarded by prop
### Access Control ### Access Control
If your Mac has a Secure Enclave, it also has support for strong access controls like Touch ID, or authentication with Apple Watch. You can configure your keys so that they require Touch ID (or Watch) authentication before they're accessed. If your Mac has a Secure Enclave, it also has support for strong access controls like Touch ID, or authentication with Apple Watch. You can configure your key so that they require Touch ID (or Watch) authentication before they're accessed.
<img src="/.github/readme/touchid.png" alt="Screenshot of Secretive authenticating with Touch ID" width="400"> <img src="/.github/readme/touchid.png" alt="Screenshot of Secretive authenticating with Touch ID">
### Notifications ### Notifications
Secretive also notifies you whenever your keys are accessed, so you're never caught off guard. Secretive also notifies you whenever your keys are accessed, so you're never caught off guard.
<img src="/.github/readme/notification.png" alt="Screenshot of Secretive notifying the user" width="600"> <img src="/.github/readme/notification.png" alt="Screenshot of Secretive notifying the user">
### Support for Smart Cards Too! ### Support for Smart Cards Too!

View File

@ -1,4 +1,4 @@
// swift-tools-version:6.0 // swift-tools-version:5.5
// The swift-tools-version declares the minimum version of Swift required to build this package. // The swift-tools-version declares the minimum version of Swift required to build this package.
import PackageDescription import PackageDescription
@ -6,7 +6,7 @@ import PackageDescription
let package = Package( let package = Package(
name: "SecretivePackages", name: "SecretivePackages",
platforms: [ platforms: [
.macOS(.v15) .macOS(.v11)
], ],
products: [ products: [
.library( .library(
@ -33,28 +33,23 @@ let package = Package(
targets: [ targets: [
.target( .target(
name: "SecretKit", name: "SecretKit",
dependencies: [], dependencies: []
swiftSettings: swiftSettings
), ),
.testTarget( .testTarget(
name: "SecretKitTests", name: "SecretKitTests",
dependencies: ["SecretKit", "SecureEnclaveSecretKit", "SmartCardSecretKit"], dependencies: ["SecretKit", "SecureEnclaveSecretKit", "SmartCardSecretKit"]
swiftSettings: swiftSettings
), ),
.target( .target(
name: "SecureEnclaveSecretKit", name: "SecureEnclaveSecretKit",
dependencies: ["SecretKit"], dependencies: ["SecretKit"]
swiftSettings: swiftSettings
), ),
.target( .target(
name: "SmartCardSecretKit", name: "SmartCardSecretKit",
dependencies: ["SecretKit"], dependencies: ["SecretKit"]
swiftSettings: swiftSettings
), ),
.target( .target(
name: "SecretAgentKit", name: "SecretAgentKit",
dependencies: ["SecretKit", "SecretAgentKitHeaders"], dependencies: ["SecretKit", "SecretAgentKitHeaders"]
swiftSettings: swiftSettings
), ),
.systemLibrary( .systemLibrary(
name: "SecretAgentKitHeaders" name: "SecretAgentKitHeaders"
@ -73,10 +68,3 @@ let package = Package(
), ),
] ]
) )
var swiftSettings: [PackageDescription.SwiftSetting] {
[
.swiftLanguageMode(.v6),
.unsafeFlags(["-warnings-as-errors"])
]
}

View File

@ -11,5 +11,5 @@ Brief is a collection of protocols and concrete implmentation describing updates
### Updater ### Updater
- ``UpdaterProtocol`` - ``UpdateCheckerProtocol``
- ``Updater`` - ``UpdateChecker``

View File

@ -1,7 +1,7 @@
import Foundation import Foundation
/// A release is a representation of a downloadable update. /// A release is a representation of a downloadable update.
public struct Release: Codable, Sendable { public struct Release: Codable {
/// The user-facing name of the release. Typically "Secretive 1.2.3" /// The user-facing name of the release. Typically "Secretive 1.2.3"
public let name: String public let name: String

View File

@ -1,7 +1,7 @@
import Foundation import Foundation
/// A representation of a Semantic Version. /// A representation of a Semantic Version.
public struct SemVer: Sendable { public struct SemVer {
/// The SemVer broken into an array of integers. /// The SemVer broken into an array of integers.
let versionNumbers: [Int] let versionNumbers: [Int]

View File

@ -1,14 +1,10 @@
import Foundation import Foundation
import Observation import Combine
import Synchronization
/// A concrete implementation of ``UpdaterProtocol`` which considers the current release and OS version. /// A concrete implementation of ``UpdateCheckerProtocol`` which considers the current release and OS version.
@Observable public final class Updater: UpdaterProtocol, ObservableObject, Sendable { public class UpdateChecker: ObservableObject, UpdateCheckerProtocol {
public var update: Release? { @Published public var update: Release?
_update.withLock { $0 }
}
private let _update: Mutex<Release?> = .init(nil)
public let testBuild: Bool public let testBuild: Bool
/// The current OS version. /// The current OS version.
@ -28,44 +24,40 @@ import Synchronization
testBuild = currentVersion == SemVer("0.0.0") testBuild = currentVersion == SemVer("0.0.0")
if checkOnLaunch { if checkOnLaunch {
// Don't do a launch check if the user hasn't seen the setup prompt explaining updater yet. // Don't do a launch check if the user hasn't seen the setup prompt explaining updater yet.
Task { checkForUpdates()
await checkForUpdates()
}
} }
Task { let timer = Timer.scheduledTimer(withTimeInterval: checkFrequency, repeats: true) { _ in
while !Task.isCancelled { self.checkForUpdates()
try? await Task.sleep(for: .seconds(Int(checkFrequency)))
await checkForUpdates()
}
} }
timer.tolerance = 60*60
} }
/// Manually trigger an update check. /// Manually trigger an update check.
public func checkForUpdates() async { public func checkForUpdates() {
guard let (data, _) = try? await URLSession.shared.data(from: Constants.updateURL) else { return } URLSession.shared.dataTask(with: Constants.updateURL) { data, _, _ in
guard let releases = try? JSONDecoder().decode([Release].self, from: data) else { return } guard let data = data else { return }
await evaluate(releases: releases) guard let releases = try? JSONDecoder().decode([Release].self, from: data) else { return }
self.evaluate(releases: releases)
}.resume()
} }
/// Ignores a specified release. `update` will be nil if the user has ignored the latest available release. /// Ignores a specified release. `update` will be nil if the user has ignored the latest available release.
/// - Parameter release: The release to ignore. /// - Parameter release: The release to ignore.
public func ignore(release: Release) async { public func ignore(release: Release) {
guard !release.critical else { return } guard !release.critical else { return }
defaults.set(true, forKey: release.name) defaults.set(true, forKey: release.name)
await MainActor.run { DispatchQueue.main.async {
_update.withLock { value in self.update = nil
value = nil
}
} }
} }
} }
extension Updater { extension UpdateChecker {
/// Evaluates the available downloadable releases, and selects the newest non-prerelease release that the user is able to run. /// Evaluates the available downloadable releases, and selects the newest non-prerelease release that the user is able to run.
/// - Parameter releases: An array of ``Release`` objects. /// - Parameter releases: An array of ``Release`` objects.
func evaluate(releases: [Release]) async { func evaluate(releases: [Release]) {
guard let release = releases guard let release = releases
.sorted() .sorted()
.reversed() .reversed()
@ -75,10 +67,8 @@ extension Updater {
guard !release.prerelease else { return } guard !release.prerelease else { return }
let latestVersion = SemVer(release.name) let latestVersion = SemVer(release.name)
if latestVersion > currentVersion { if latestVersion > currentVersion {
await MainActor.run { DispatchQueue.main.async {
_update.withLock { value in self.update = release
value = release
}
} }
} }
} }
@ -98,7 +88,7 @@ extension Updater {
} }
extension Updater { extension UpdateChecker {
enum Constants { enum Constants {
static let updateURL = URL(string: "https://api.github.com/repos/maxgoedjen/secretive/releases")! static let updateURL = URL(string: "https://api.github.com/repos/maxgoedjen/secretive/releases")!

View File

@ -1,8 +1,7 @@
import Foundation import Foundation
import Synchronization
/// A protocol for retreiving the latest available version of an app. /// A protocol for retreiving the latest available version of an app.
public protocol UpdaterProtocol: Observable { public protocol UpdateCheckerProtocol: ObservableObject {
/// The latest update /// The latest update
var update: Release? { get } var update: Release? { get }

View File

@ -5,24 +5,21 @@ import SecretKit
import AppKit import AppKit
/// The `Agent` is an implementation of an SSH agent. It manages coordination and access between a socket, traces requests, notifies witnesses and passes requests to stores. /// The `Agent` is an implementation of an SSH agent. It manages coordination and access between a socket, traces requests, notifies witnesses and passes requests to stores.
public final class Agent: Sendable { public class Agent {
private let storeList: SecretStoreList private let storeList: SecretStoreList
private let witness: SigningWitness? private let witness: SigningWitness?
private let writer = OpenSSHKeyWriter() private let writer = OpenSSHKeyWriter()
private let requestTracer = SigningRequestTracer() private let requestTracer = SigningRequestTracer()
private let certificateHandler = OpenSSHCertificateHandler()
private let logger = Logger(subsystem: "com.maxgoedjen.secretive.secretagent", category: "Agent")
/// Initializes an agent with a store list and a witness. /// Initializes an agent with a store list and a witness.
/// - Parameters: /// - Parameters:
/// - storeList: The `SecretStoreList` to make available. /// - storeList: The `SecretStoreList` to make available.
/// - witness: A witness to notify of requests. /// - witness: A witness to notify of requests.
public init(storeList: SecretStoreList, witness: SigningWitness? = nil) { public init(storeList: SecretStoreList, witness: SigningWitness? = nil) {
logger.debug("Agent is running") Logger().debug("Agent is running")
self.storeList = storeList self.storeList = storeList
self.witness = witness self.witness = witness
certificateHandler.reloadCertificates(for: storeList.allSecrets)
} }
} }
@ -35,43 +32,41 @@ extension Agent {
/// - writer: A ``FileHandleWriter`` to write the response to. /// - writer: A ``FileHandleWriter`` to write the response to.
/// - Return value: /// - Return value:
/// - Boolean if data could be read /// - Boolean if data could be read
@discardableResult public func handle(reader: FileHandleReader, writer: FileHandleWriter) async -> Bool { public func handle(reader: FileHandleReader, writer: FileHandleWriter) -> Bool {
logger.debug("Agent handling new data") Logger().debug("Agent handling new data")
let data = Data(reader.availableData) let data = Data(reader.availableData)
guard data.count > 4 else { return false} guard data.count > 4 else { return false}
let requestTypeInt = data[4] let requestTypeInt = data[4]
guard let requestType = SSHAgent.RequestType(rawValue: requestTypeInt) else { guard let requestType = SSHAgent.RequestType(rawValue: requestTypeInt) else {
writer.write(OpenSSHKeyWriter().lengthAndData(of: SSHAgent.ResponseType.agentFailure.data)) writer.write(OpenSSHKeyWriter().lengthAndData(of: SSHAgent.ResponseType.agentFailure.data))
logger.debug("Agent returned \(SSHAgent.ResponseType.agentFailure.debugDescription)") Logger().debug("Agent returned \(SSHAgent.ResponseType.agentFailure.debugDescription)")
return true return true
} }
logger.debug("Agent handling request of type \(requestType.debugDescription)") Logger().debug("Agent handling request of type \(requestType.debugDescription)")
let subData = Data(data[5...]) let subData = Data(data[5...])
let response = await handle(requestType: requestType, data: subData, reader: reader) let response = handle(requestType: requestType, data: subData, reader: reader)
writer.write(response) writer.write(response)
return true return true
} }
func handle(requestType: SSHAgent.RequestType, data: Data, reader: FileHandleReader) async -> Data { func handle(requestType: SSHAgent.RequestType, data: Data, reader: FileHandleReader) -> Data {
// Depending on the launch context (such as after macOS update), the agent may need to reload secrets before acting
await reloadSecretsIfNeccessary()
var response = Data() var response = Data()
do { do {
switch requestType { switch requestType {
case .requestIdentities: case .requestIdentities:
response.append(SSHAgent.ResponseType.agentIdentitiesAnswer.data) response.append(SSHAgent.ResponseType.agentIdentitiesAnswer.data)
response.append(identities()) response.append(identities())
logger.debug("Agent returned \(SSHAgent.ResponseType.agentIdentitiesAnswer.debugDescription)") Logger().debug("Agent returned \(SSHAgent.ResponseType.agentIdentitiesAnswer.debugDescription)")
case .signRequest: case .signRequest:
let provenance = requestTracer.provenance(from: reader) let provenance = requestTracer.provenance(from: reader)
response.append(SSHAgent.ResponseType.agentSignResponse.data) response.append(SSHAgent.ResponseType.agentSignResponse.data)
response.append(try await sign(data: data, provenance: provenance)) response.append(try sign(data: data, provenance: provenance))
logger.debug("Agent returned \(SSHAgent.ResponseType.agentSignResponse.debugDescription)") Logger().debug("Agent returned \(SSHAgent.ResponseType.agentSignResponse.debugDescription)")
} }
} catch { } catch {
response.removeAll() response.removeAll()
response.append(SSHAgent.ResponseType.agentFailure.data) response.append(SSHAgent.ResponseType.agentFailure.data)
logger.debug("Agent returned \(SSHAgent.ResponseType.agentFailure.debugDescription)") Logger().debug("Agent returned \(SSHAgent.ResponseType.agentFailure.debugDescription)")
} }
let full = OpenSSHKeyWriter().lengthAndData(of: response) let full = OpenSSHKeyWriter().lengthAndData(of: response)
return full return full
@ -84,26 +79,18 @@ extension Agent {
/// Lists the identities available for signing operations /// Lists the identities available for signing operations
/// - Returns: An OpenSSH formatted Data payload listing the identities available for signing operations. /// - Returns: An OpenSSH formatted Data payload listing the identities available for signing operations.
func identities() -> Data { func identities() -> Data {
let secrets = storeList.allSecrets let secrets = storeList.stores.flatMap(\.secrets)
certificateHandler.reloadCertificates(for: secrets) var count = UInt32(secrets.count).bigEndian
var count = secrets.count let countData = Data(bytes: &count, count: UInt32.bitWidth/8)
var keyData = Data() var keyData = Data()
let writer = OpenSSHKeyWriter()
for secret in secrets { for secret in secrets {
let keyBlob = writer.data(secret: secret) let keyBlob = writer.data(secret: secret)
let curveData = writer.curveType(for: secret.algorithm, length: secret.keySize).data(using: .utf8)!
keyData.append(writer.lengthAndData(of: keyBlob)) keyData.append(writer.lengthAndData(of: keyBlob))
let curveData = writer.curveType(for: secret.algorithm, length: secret.keySize).data(using: .utf8)!
keyData.append(writer.lengthAndData(of: curveData)) keyData.append(writer.lengthAndData(of: curveData))
if let (certificateData, name) = try? certificateHandler.keyBlobAndName(for: secret) {
keyData.append(writer.lengthAndData(of: certificateData))
keyData.append(writer.lengthAndData(of: name))
count += 1
}
} }
logger.log("Agent enumerated \(count) identities") Logger().debug("Agent enumerated \(secrets.count) identities")
var countBigEndian = UInt32(count).bigEndian
let countData = Data(bytes: &countBigEndian, count: UInt32.bitWidth/8)
return countData + keyData return countData + keyData
} }
@ -112,29 +99,21 @@ extension Agent {
/// - data: The data to sign. /// - data: The data to sign.
/// - provenance: A ``SecretKit.SigningRequestProvenance`` object describing the origin of the request. /// - provenance: A ``SecretKit.SigningRequestProvenance`` object describing the origin of the request.
/// - Returns: An OpenSSH formatted Data payload containing the signed data response. /// - Returns: An OpenSSH formatted Data payload containing the signed data response.
func sign(data: Data, provenance: SigningRequestProvenance) async throws -> Data { func sign(data: Data, provenance: SigningRequestProvenance) throws -> Data {
let reader = OpenSSHReader(data: data) let reader = OpenSSHReader(data: data)
let payloadHash = reader.readNextChunk() let hash = reader.readNextChunk()
let hash: Data
// Check if hash is actually an openssh certificate and reconstruct the public key if it is
if let certificatePublicKey = certificateHandler.publicKeyHash(from: payloadHash) {
hash = certificatePublicKey
} else {
hash = payloadHash
}
guard let (store, secret) = secret(matching: hash) else { guard let (store, secret) = secret(matching: hash) else {
logger.debug("Agent did not have a key matching \(hash as NSData)") Logger().debug("Agent did not have a key matching \(hash as NSData)")
throw AgentError.noMatchingKey throw AgentError.noMatchingKey
} }
if let witness = witness { if let witness = witness {
try await witness.speakNowOrForeverHoldYourPeace(forAccessTo: secret, from: store, by: provenance) try witness.speakNowOrForeverHoldYourPeace(forAccessTo: secret, from: store, by: provenance)
} }
let dataToSign = reader.readNextChunk() let dataToSign = reader.readNextChunk()
let signed = try await store.sign(data: dataToSign, with: secret, for: provenance) let signed = try store.sign(data: dataToSign, with: secret, for: provenance)
let derSignature = signed let derSignature = signed.data
let curveData = writer.curveType(for: secret.algorithm, length: secret.keySize).data(using: .utf8)! let curveData = writer.curveType(for: secret.algorithm, length: secret.keySize).data(using: .utf8)!
@ -175,10 +154,10 @@ extension Agent {
signedData.append(writer.lengthAndData(of: sub)) signedData.append(writer.lengthAndData(of: sub))
if let witness = witness { if let witness = witness {
try await witness.witness(accessTo: secret, from: store, by: provenance) try witness.witness(accessTo: secret, from: store, by: provenance, requiredAuthentication: signed.requiredAuthentication)
} }
logger.debug("Agent signed request") Logger().debug("Agent signed request")
return signedData return signedData
} }
@ -187,16 +166,6 @@ extension Agent {
extension Agent { extension Agent {
/// Gives any store with no loaded secrets a chance to reload.
func reloadSecretsIfNeccessary() async {
for store in storeList.stores {
if store.secrets.isEmpty {
logger.debug("Store \(store.name, privacy: .public) has no loaded secrets. Reloading.")
await store.reloadSecrets()
}
}
}
/// Finds a ``Secret`` matching a specified hash whos signature was requested. /// Finds a ``Secret`` matching a specified hash whos signature was requested.
/// - Parameter hash: The hash to match against. /// - Parameter hash: The hash to match against.
/// - Returns: A ``Secret`` and the ``SecretStore`` containing it, if a match is found. /// - Returns: A ``Secret`` and the ``SecretStore`` containing it, if a match is found.
@ -222,7 +191,6 @@ extension Agent {
case unhandledType case unhandledType
case noMatchingKey case noMatchingKey
case unsupportedKeyType case unsupportedKeyType
case notOpenSSHCertificate
} }
} }

View File

@ -1,7 +1,7 @@
import Foundation import Foundation
/// Protocol abstraction of the reading aspects of FileHandle. /// Protocol abstraction of the reading aspects of FileHandle.
public protocol FileHandleReader: Sendable { public protocol FileHandleReader {
/// Gets data that is available for reading. /// Gets data that is available for reading.
var availableData: Data { get } var availableData: Data { get }
@ -13,7 +13,7 @@ public protocol FileHandleReader: Sendable {
} }
/// Protocol abstraction of the writing aspects of FileHandle. /// Protocol abstraction of the writing aspects of FileHandle.
public protocol FileHandleWriter: Sendable { public protocol FileHandleWriter {
/// Writes data to the handle. /// Writes data to the handle.
func write(_ data: Data) func write(_ data: Data)

View File

@ -1,11 +1,11 @@
import Foundation import Foundation
/// A namespace for the SSH Agent Protocol, as described in https://datatracker.ietf.org/doc/html/draft-miller-ssh-agent#section-5.1 /// A namespace for the SSH Agent Protocol, as described in https://tools.ietf.org/id/draft-miller-ssh-agent-01.html
public enum SSHAgent {} public enum SSHAgent {}
extension SSHAgent { extension SSHAgent {
/// The type of the SSH Agent Request, as described in https://datatracker.ietf.org/doc/html/draft-miller-ssh-agent#section-5.1 /// The type of the SSH Agent Request, as described in https://tools.ietf.org/id/draft-miller-ssh-agent-01.html#rfc.section.5.1
public enum RequestType: UInt8, CustomDebugStringConvertible { public enum RequestType: UInt8, CustomDebugStringConvertible {
case requestIdentities = 11 case requestIdentities = 11
@ -21,11 +21,10 @@ extension SSHAgent {
} }
} }
/// The type of the SSH Agent Response, as described in https://datatracker.ietf.org/doc/html/draft-miller-ssh-agent#section-5.1 /// The type of the SSH Agent Response, as described in https://tools.ietf.org/id/draft-miller-ssh-agent-01.html#rfc.section.5.1
public enum ResponseType: UInt8, CustomDebugStringConvertible { public enum ResponseType: UInt8, CustomDebugStringConvertible {
case agentFailure = 5 case agentFailure = 5
case agentSuccess = 6
case agentIdentitiesAnswer = 12 case agentIdentitiesAnswer = 12
case agentSignResponse = 14 case agentSignResponse = 14
@ -33,8 +32,6 @@ extension SSHAgent {
switch self { switch self {
case .agentFailure: case .agentFailure:
return "AgentFailure" return "AgentFailure"
case .agentSuccess:
return "AgentSuccess"
case .agentIdentitiesAnswer: case .agentIdentitiesAnswer:
return "AgentIdentitiesAnswer" return "AgentIdentitiesAnswer"
case .agentSignResponse: case .agentSignResponse:

View File

@ -1,11 +0,0 @@
import Foundation
struct UncheckedSendable<T>: @unchecked Sendable {
let value: T
init(_ value: T) {
self.value = value
}
}

View File

@ -40,10 +40,7 @@ extension SigningRequestTracer {
func process(from pid: Int32) -> SigningRequestProvenance.Process { func process(from pid: Int32) -> SigningRequestProvenance.Process {
var pidAndNameInfo = self.pidAndNameInfo(from: pid) var pidAndNameInfo = self.pidAndNameInfo(from: pid)
let ppid = pidAndNameInfo.kp_eproc.e_ppid != 0 ? pidAndNameInfo.kp_eproc.e_ppid : nil let ppid = pidAndNameInfo.kp_eproc.e_ppid != 0 ? pidAndNameInfo.kp_eproc.e_ppid : nil
let procName = withUnsafeMutablePointer(to: &pidAndNameInfo.kp_proc.p_comm.0) { pointer in let procName = String(cString: &pidAndNameInfo.kp_proc.p_comm.0)
String(cString: pointer)
}
let pathPointer = UnsafeMutablePointer<UInt8>.allocate(capacity: Int(MAXPATHLEN)) let pathPointer = UnsafeMutablePointer<UInt8>.allocate(capacity: Int(MAXPATHLEN))
_ = proc_pidpath(pid, pathPointer, UInt32(MAXPATHLEN)) _ = proc_pidpath(pid, pathPointer, UInt32(MAXPATHLEN))
let path = String(cString: pathPointer) let path = String(cString: pathPointer)
@ -60,10 +57,7 @@ extension SigningRequestTracer {
func iconURL(for pid: Int32) -> URL? { func iconURL(for pid: Int32) -> URL? {
do { do {
if let app = NSRunningApplication(processIdentifier: pid), let icon = app.icon?.tiffRepresentation { if let app = NSRunningApplication(processIdentifier: pid), let icon = app.icon?.tiffRepresentation {
let temporaryURL = URL(fileURLWithPath: (NSTemporaryDirectory() as NSString).appendingPathComponent("\(app.bundleIdentifier ?? UUID().uuidString).png")) let temporaryURL = URL(fileURLWithPath: (NSTemporaryDirectory() as NSString).appendingPathComponent("\(UUID().uuidString).png"))
if FileManager.default.fileExists(atPath: temporaryURL.path) {
return temporaryURL
}
let bitmap = NSBitmapImageRep(data: icon) let bitmap = NSBitmapImageRep(data: icon)
try bitmap?.representation(using: .png, properties: [:])?.write(to: temporaryURL) try bitmap?.representation(using: .png, properties: [:])?.write(to: temporaryURL)
return temporaryURL return temporaryURL

View File

@ -2,7 +2,7 @@ import Foundation
import SecretKit import SecretKit
/// A protocol that allows conformers to be notified of access to secrets, and optionally prevent access. /// A protocol that allows conformers to be notified of access to secrets, and optionally prevent access.
public protocol SigningWitness: Sendable { public protocol SigningWitness {
/// A ridiculously named method that notifies the callee that a signing operation is about to be performed using a secret. The callee may `throw` an `Error` to prevent access from occurring. /// A ridiculously named method that notifies the callee that a signing operation is about to be performed using a secret. The callee may `throw` an `Error` to prevent access from occurring.
/// - Parameters: /// - Parameters:
@ -10,13 +10,14 @@ public protocol SigningWitness: Sendable {
/// - store: The `Store` being asked to sign the request.. /// - store: The `Store` being asked to sign the request..
/// - provenance: A `SigningRequestProvenance` object describing the origin of the request. /// - provenance: A `SigningRequestProvenance` object describing the origin of the request.
/// - Note: This method being called does not imply that the requst has been authorized. If a secret requires authentication, authentication will still need to be performed by the user before the request will be performed. If the user declines or fails to authenticate, the request will fail. /// - Note: This method being called does not imply that the requst has been authorized. If a secret requires authentication, authentication will still need to be performed by the user before the request will be performed. If the user declines or fails to authenticate, the request will fail.
func speakNowOrForeverHoldYourPeace(forAccessTo secret: AnySecret, from store: AnySecretStore, by provenance: SigningRequestProvenance) async throws func speakNowOrForeverHoldYourPeace(forAccessTo secret: AnySecret, from store: AnySecretStore, by provenance: SigningRequestProvenance) throws
/// Notifies the callee that a signing operation has been performed for a given secret. /// Notifies the callee that a signing operation has been performed for a given secret.
/// - Parameters: /// - Parameters:
/// - secret: The `Secret` that will was used to sign the request. /// - secret: The `Secret` that will was used to sign the request.
/// - store: The `Store` that signed the request.. /// - store: The `Store` that signed the request..
/// - provenance: A `SigningRequestProvenance` object describing the origin of the request. /// - provenance: A `SigningRequestProvenance` object describing the origin of the request.
func witness(accessTo secret: AnySecret, from store: AnySecretStore, by provenance: SigningRequestProvenance) async throws /// - requiredAuthentication: A boolean describing whether or not authentication was required for the request.
func witness(accessTo secret: AnySecret, from store: AnySecretStore, by provenance: SigningRequestProvenance, requiredAuthentication: Bool) throws
} }

View File

@ -2,7 +2,7 @@ import Foundation
import OSLog import OSLog
/// A controller that manages socket configuration and request dispatching. /// A controller that manages socket configuration and request dispatching.
public final class SocketController { public class SocketController {
/// The active FileHandle. /// The active FileHandle.
private var fileHandle: FileHandle? private var fileHandle: FileHandle?
@ -10,24 +10,22 @@ public final class SocketController {
private var port: SocketPort? private var port: SocketPort?
/// A handler that will be notified when a new read/write handle is available. /// A handler that will be notified when a new read/write handle is available.
/// False if no data could be read /// False if no data could be read
public var handler: (@Sendable (FileHandleReader, FileHandleWriter) async -> Bool)? public var handler: ((FileHandleReader, FileHandleWriter) -> Bool)?
/// Logger.
private let logger = Logger(subsystem: "com.maxgoedjen.secretive.secretagent", category: "SocketController")
/// Initializes a socket controller with a specified path. /// Initializes a socket controller with a specified path.
/// - Parameter path: The path to use as a socket. /// - Parameter path: The path to use as a socket.
public init(path: String) { public init(path: String) {
logger.debug("Socket controller setting up at \(path)") Logger().debug("Socket controller setting up at \(path)")
if let _ = try? FileManager.default.removeItem(atPath: path) { if let _ = try? FileManager.default.removeItem(atPath: path) {
logger.debug("Socket controller removed existing socket") Logger().debug("Socket controller removed existing socket")
} }
let exists = FileManager.default.fileExists(atPath: path) let exists = FileManager.default.fileExists(atPath: path)
assert(!exists) assert(!exists)
logger.debug("Socket controller path is clear") Logger().debug("Socket controller path is clear")
port = socketPort(at: path) port = socketPort(at: path)
configureSocket(at: path) configureSocket(at: path)
logger.debug("Socket listening at \(path)") Logger().debug("Socket listening at \(path)")
} }
/// Configures the socket and a corresponding FileHandle. /// Configures the socket and a corresponding FileHandle.
@ -37,7 +35,7 @@ public final class SocketController {
fileHandle = FileHandle(fileDescriptor: port.socket, closeOnDealloc: true) fileHandle = FileHandle(fileDescriptor: port.socket, closeOnDealloc: true)
NotificationCenter.default.addObserver(self, selector: #selector(handleConnectionAccept(notification:)), name: .NSFileHandleConnectionAccepted, object: nil) NotificationCenter.default.addObserver(self, selector: #selector(handleConnectionAccept(notification:)), name: .NSFileHandleConnectionAccepted, object: nil)
NotificationCenter.default.addObserver(self, selector: #selector(handleConnectionDataAvailable(notification:)), name: .NSFileHandleDataAvailable, object: nil) NotificationCenter.default.addObserver(self, selector: #selector(handleConnectionDataAvailable(notification:)), name: .NSFileHandleDataAvailable, object: nil)
fileHandle?.acceptConnectionInBackgroundAndNotify(forModes: [RunLoop.Mode.common]) fileHandle?.acceptConnectionInBackgroundAndNotify(forModes: [RunLoop.current.currentMode!])
} }
/// Creates a SocketPort for a path. /// Creates a SocketPort for a path.
@ -67,45 +65,25 @@ public final class SocketController {
/// Handles a new connection being accepted, invokes the handler, and prepares to accept new connections. /// Handles a new connection being accepted, invokes the handler, and prepares to accept new connections.
/// - Parameter notification: A `Notification` that triggered the call. /// - Parameter notification: A `Notification` that triggered the call.
@objc func handleConnectionAccept(notification: Notification) { @objc func handleConnectionAccept(notification: Notification) {
logger.debug("Socket controller accepted connection") Logger().debug("Socket controller accepted connection")
guard let new = notification.userInfo?[NSFileHandleNotificationFileHandleItem] as? FileHandle else { return } guard let new = notification.userInfo?[NSFileHandleNotificationFileHandleItem] as? FileHandle else { return }
Task { [handler, fileHandle] in _ = handler?(new, new)
_ = await handler?(new, new) new.waitForDataInBackgroundAndNotify()
await new.waitForDataInBackgroundAndNotifyOnMainActor() fileHandle?.acceptConnectionInBackgroundAndNotify(forModes: [RunLoop.current.currentMode!])
await fileHandle?.acceptConnectionInBackgroundAndNotifyOnMainActor()
}
} }
/// Handles a new connection providing data and invokes the handler callback. /// Handles a new connection providing data and invokes the handler callback.
/// - Parameter notification: A `Notification` that triggered the call. /// - Parameter notification: A `Notification` that triggered the call.
@objc func handleConnectionDataAvailable(notification: Notification) { @objc func handleConnectionDataAvailable(notification: Notification) {
logger.debug("Socket controller has new data available") Logger().debug("Socket controller has new data available")
guard let new = notification.object as? FileHandle else { return } guard let new = notification.object as? FileHandle else { return }
logger.debug("Socket controller received new file handle") Logger().debug("Socket controller received new file handle")
Task { [handler, logger = UncheckedSendable(logger)] in if((handler?(new, new)) == true) {
if((await handler?(new, new)) == true) { Logger().debug("Socket controller handled data, wait for more data")
logger.value.debug("Socket controller handled data, wait for more data") new.waitForDataInBackgroundAndNotify()
await new.waitForDataInBackgroundAndNotifyOnMainActor() } else {
} else { Logger().debug("Socket controller called with empty data, socked closed")
logger.value.debug("Socket controller called with empty data, socked closed")
}
} }
} }
} }
extension FileHandle {
/// Ensures waitForDataInBackgroundAndNotify will be called on the main actor.
@MainActor func waitForDataInBackgroundAndNotifyOnMainActor() {
waitForDataInBackgroundAndNotify()
}
/// Ensures acceptConnectionInBackgroundAndNotify will be called on the main actor.
/// - Parameter modes: the runloop modes to use.
@MainActor func acceptConnectionInBackgroundAndNotifyOnMainActor(forModes modes: [RunLoop.Mode]? = [RunLoop.Mode.common]) {
acceptConnectionInBackgroundAndNotify(forModes: modes)
}
}

View File

@ -27,14 +27,5 @@ SecretKit is a collection of protocols describing secrets and stores.
### Signing Process ### Signing Process
- ``SignedData``
- ``SigningRequestProvenance`` - ``SigningRequestProvenance``
### Authentication Persistence
- ``PersistedAuthenticationContext``
### Errors
- ``KeychainError``
- ``SigningError``
- ``SecurityError``

View File

@ -1,7 +1,7 @@
import Foundation import Foundation
/// Type eraser for Secret. /// Type eraser for Secret.
public struct AnySecret: Secret, @unchecked Sendable { public struct AnySecret: Secret {
let base: Any let base: Any
private let hashable: AnyHashable private let hashable: AnyHashable
@ -9,7 +9,6 @@ public struct AnySecret: Secret, @unchecked Sendable {
private let _name: () -> String private let _name: () -> String
private let _algorithm: () -> Algorithm private let _algorithm: () -> Algorithm
private let _keySize: () -> Int private let _keySize: () -> Int
private let _requiresAuthentication: () -> Bool
private let _publicKey: () -> Data private let _publicKey: () -> Data
public init<T>(_ secret: T) where T: Secret { public init<T>(_ secret: T) where T: Secret {
@ -20,7 +19,6 @@ public struct AnySecret: Secret, @unchecked Sendable {
_name = secret._name _name = secret._name
_algorithm = secret._algorithm _algorithm = secret._algorithm
_keySize = secret._keySize _keySize = secret._keySize
_requiresAuthentication = secret._requiresAuthentication
_publicKey = secret._publicKey _publicKey = secret._publicKey
} else { } else {
base = secret as Any base = secret as Any
@ -29,7 +27,6 @@ public struct AnySecret: Secret, @unchecked Sendable {
_name = { secret.name } _name = { secret.name }
_algorithm = { secret.algorithm } _algorithm = { secret.algorithm }
_keySize = { secret.keySize } _keySize = { secret.keySize }
_requiresAuthentication = { secret.requiresAuthentication }
_publicKey = { secret.publicKey } _publicKey = { secret.publicKey }
} }
} }
@ -50,10 +47,6 @@ public struct AnySecret: Secret, @unchecked Sendable {
_keySize() _keySize()
} }
public var requiresAuthentication: Bool {
_requiresAuthentication()
}
public var publicKey: Data { public var publicKey: Data {
_publicKey() _publicKey()
} }

View File

@ -2,18 +2,17 @@ import Foundation
import Combine import Combine
/// Type eraser for SecretStore. /// Type eraser for SecretStore.
public class AnySecretStore: SecretStore, @unchecked Sendable { public class AnySecretStore: SecretStore {
let base: Any let base: Any
private let _isAvailable: @Sendable () -> Bool private let _isAvailable: () -> Bool
private let _id: @Sendable () -> UUID private let _id: () -> UUID
private let _name: @Sendable () -> String private let _name: () -> String
private let _secrets: @Sendable () -> [AnySecret] private let _secrets: () -> [AnySecret]
private let _sign: @Sendable (Data, AnySecret, SigningRequestProvenance) async throws -> Data private let _sign: (Data, AnySecret, SigningRequestProvenance) throws -> SignedData
private let _verify: @Sendable (Data, Data, AnySecret) async throws -> Bool private let _persistAuthentication: (AnySecret, TimeInterval) throws -> Void
private let _existingPersistedAuthenticationContext: @Sendable (AnySecret) async -> PersistedAuthenticationContext?
private let _persistAuthentication: @Sendable (AnySecret, TimeInterval) async throws -> Void private var sink: AnyCancellable?
private let _reloadSecrets: @Sendable () async -> Void
public init<SecretStoreType>(_ secretStore: SecretStoreType) where SecretStoreType: SecretStore { public init<SecretStoreType>(_ secretStore: SecretStoreType) where SecretStoreType: SecretStore {
base = secretStore base = secretStore
@ -21,11 +20,11 @@ public class AnySecretStore: SecretStore, @unchecked Sendable {
_name = { secretStore.name } _name = { secretStore.name }
_id = { secretStore.id } _id = { secretStore.id }
_secrets = { secretStore.secrets.map { AnySecret($0) } } _secrets = { secretStore.secrets.map { AnySecret($0) } }
_sign = { try await secretStore.sign(data: $0, with: $1.base as! SecretStoreType.SecretType, for: $2) } _sign = { try secretStore.sign(data: $0, with: $1.base as! SecretStoreType.SecretType, for: $2) }
_verify = { try await secretStore.verify(signature: $0, for: $1, with: $2.base as! SecretStoreType.SecretType) } _persistAuthentication = { try secretStore.persistAuthentication(secret: $0.base as! SecretStoreType.SecretType, forDuration: $1) }
_existingPersistedAuthenticationContext = { await secretStore.existingPersistedAuthenticationContext(secret: $0.base as! SecretStoreType.SecretType) } sink = secretStore.objectWillChange.sink { _ in
_persistAuthentication = { try await secretStore.persistAuthentication(secret: $0.base as! SecretStoreType.SecretType, forDuration: $1) } self.objectWillChange.send()
_reloadSecrets = { await secretStore.reloadSecrets() } }
} }
public var isAvailable: Bool { public var isAvailable: Bool {
@ -44,51 +43,39 @@ public class AnySecretStore: SecretStore, @unchecked Sendable {
return _secrets() return _secrets()
} }
public func sign(data: Data, with secret: AnySecret, for provenance: SigningRequestProvenance) async throws -> Data { public func sign(data: Data, with secret: AnySecret, for provenance: SigningRequestProvenance) throws -> SignedData {
try await _sign(data, secret, provenance) try _sign(data, secret, provenance)
} }
public func verify(signature: Data, for data: Data, with secret: AnySecret) async throws -> Bool { public func persistAuthentication(secret: AnySecret, forDuration duration: TimeInterval) throws {
try await _verify(signature, data, secret) try _persistAuthentication(secret, duration)
}
public func existingPersistedAuthenticationContext(secret: AnySecret) async -> PersistedAuthenticationContext? {
await _existingPersistedAuthenticationContext(secret)
}
public func persistAuthentication(secret: AnySecret, forDuration duration: TimeInterval) async throws {
try await _persistAuthentication(secret, duration)
}
public func reloadSecrets() async {
await _reloadSecrets()
} }
} }
public final class AnySecretStoreModifiable: AnySecretStore, SecretStoreModifiable, @unchecked Sendable { public class AnySecretStoreModifiable: AnySecretStore, SecretStoreModifiable {
private let _create: @Sendable (String, Bool) async throws -> Void private let _create: (String, Bool) throws -> Void
private let _delete: @Sendable (AnySecret) async throws -> Void private let _delete: (AnySecret) throws -> Void
private let _update: @Sendable (AnySecret, String) async throws -> Void private let _update: (AnySecret, String) throws -> Void
public init<SecretStoreType>(modifiable secretStore: SecretStoreType) where SecretStoreType: SecretStoreModifiable { public init<SecretStoreType>(modifiable secretStore: SecretStoreType) where SecretStoreType: SecretStoreModifiable {
_create = { try await secretStore.create(name: $0, requiresAuthentication: $1) } _create = { try secretStore.create(name: $0, requiresAuthentication: $1) }
_delete = { try await secretStore.delete(secret: $0.base as! SecretStoreType.SecretType) } _delete = { try secretStore.delete(secret: $0.base as! SecretStoreType.SecretType) }
_update = { try await secretStore.update(secret: $0.base as! SecretStoreType.SecretType, name: $1) } _update = { try secretStore.update(secret: $0.base as! SecretStoreType.SecretType, name: $1) }
super.init(secretStore) super.init(secretStore)
} }
public func create(name: String, requiresAuthentication: Bool) async throws { public func create(name: String, requiresAuthentication: Bool) throws {
try await _create(name, requiresAuthentication) try _create(name, requiresAuthentication)
} }
public func delete(secret: AnySecret) async throws { public func delete(secret: AnySecret) throws {
try await _delete(secret) try _delete(secret)
} }
public func update(secret: AnySecret, name: String) async throws { public func update(secret: AnySecret, name: String) throws {
try await _update(secret, name) try _update(secret, name)
} }
} }

View File

@ -1,71 +0,0 @@
import Foundation
public typealias SecurityError = Unmanaged<CFError>
/// Wraps a Swift dictionary in a CFDictionary.
/// - Parameter dictionary: The Swift dictionary to wrap.
/// - Returns: A CFDictionary containing the keys and values.
public func KeychainDictionary(_ dictionary: [CFString: Any]) -> CFDictionary {
dictionary as CFDictionary
}
public extension CFError {
/// The CFError returned when a verification operation fails.
static let verifyError = CFErrorCreate(nil, NSOSStatusErrorDomain as CFErrorDomain, CFIndex(errSecVerifyFailed), nil)!
/// Equality operation that only considers domain and code.
static func ~=(lhs: CFError, rhs: CFError) -> Bool {
CFErrorGetDomain(lhs) == CFErrorGetDomain(rhs) && CFErrorGetCode(lhs) == CFErrorGetCode(rhs)
}
}
/// A wrapper around an error code reported by a Keychain API.
public struct KeychainError: Error {
/// The status code involved, if one was reported.
public let statusCode: OSStatus?
/// Initializes a KeychainError with an optional error code.
/// - Parameter statusCode: The status code returned by the keychain operation, if one is applicable.
public init(statusCode: OSStatus?) {
self.statusCode = statusCode
}
}
/// A signing-related error.
public struct SigningError: Error {
/// The underlying error reported by the API, if one was returned.
public let error: SecurityError?
/// Initializes a SigningError with an optional SecurityError.
/// - Parameter statusCode: The SecurityError, if one is applicable.
public init(error: SecurityError?) {
self.error = error
}
}
public extension SecretStore {
/// Returns the appropriate keychian signature algorithm to use for a given secret.
/// - Parameters:
/// - secret: The secret which will be used for signing.
/// - allowRSA: Whether or not RSA key types should be permited.
/// - Returns: The appropriate algorithm.
func signatureAlgorithm(for secret: SecretType, allowRSA: Bool = false) -> SecKeyAlgorithm {
switch (secret.algorithm, secret.keySize) {
case (.ellipticCurve, 256):
return .ecdsaSignatureMessageX962SHA256
case (.ellipticCurve, 384):
return .ecdsaSignatureMessageX962SHA384
case (.rsa, 1024), (.rsa, 2048):
guard allowRSA else { fatalError() }
return .rsaSignatureMessagePKCS1v15SHA512
default:
fatalError()
}
}
}

View File

@ -1,128 +0,0 @@
import Foundation
import OSLog
import Synchronization
/// Manages storage and lookup for OpenSSH certificates.
public final class OpenSSHCertificateHandler: Sendable {
private let publicKeyFileStoreController = PublicKeyFileStoreController(homeDirectory: NSHomeDirectory())
private let logger = Logger(subsystem: "com.maxgoedjen.secretive.secretagent", category: "OpenSSHCertificateHandler")
private let writer = OpenSSHKeyWriter()
private let keyBlobsAndNames: Mutex<[AnySecret: (Data, Data)]> = .init([:])
/// Initializes an OpenSSHCertificateHandler.
public init() {
}
/// Reloads any certificates in the PublicKeys folder.
/// - Parameter secrets: the secrets to look up corresponding certificates for.
public func reloadCertificates(for secrets: [AnySecret]) {
guard publicKeyFileStoreController.hasAnyCertificates else {
logger.log("No certificates, short circuiting")
return
}
keyBlobsAndNames.withLock {
$0 = secrets.reduce(into: [:]) { partialResult, next in
partialResult[next] = try? loadKeyblobAndName(for: next)
}
}
}
/// Whether or not the certificate handler has a certifiicate associated with a given secret.
/// - Parameter secret: The secret to check for a certificate.
/// - Returns: A boolean describing whether or not the certificate handler has a certifiicate associated with a given secret
public func hasCertificate<SecretType: Secret>(for secret: SecretType) -> Bool {
keyBlobsAndNames.withLock {
$0[AnySecret(secret)] != nil
}
}
/// Reconstructs a public key from a ``Data``, if that ``Data`` contains an OpenSSH certificate hash. Currently only ecdsa certificates are supported
/// - Parameter certBlock: The openssh certificate to extract the public key from
/// - Returns: A ``Data`` object containing the public key in OpenSSH wire format if the ``Data`` is an OpenSSH certificate hash, otherwise nil.
public func publicKeyHash(from hash: Data) -> Data? {
let reader = OpenSSHReader(data: hash)
let certType = String(decoding: reader.readNextChunk(), as: UTF8.self)
switch certType {
case "ecdsa-sha2-nistp256-cert-v01@openssh.com",
"ecdsa-sha2-nistp384-cert-v01@openssh.com",
"ecdsa-sha2-nistp521-cert-v01@openssh.com":
_ = reader.readNextChunk() // nonce
let curveIdentifier = reader.readNextChunk()
let publicKey = reader.readNextChunk()
let curveType = certType.replacingOccurrences(of: "-cert-v01@openssh.com", with: "").data(using: .utf8)!
return writer.lengthAndData(of: curveType) +
writer.lengthAndData(of: curveIdentifier) +
writer.lengthAndData(of: publicKey)
default:
return nil
}
}
/// Attempts to find an OpenSSH Certificate that corresponds to a ``Secret``
/// - Parameter secret: The secret to search for a certificate with
/// - Returns: A (``Data``, ``Data``) tuple containing the certificate and certificate name, respectively.
public func keyBlobAndName<SecretType: Secret>(for secret: SecretType) throws -> (Data, Data)? {
keyBlobsAndNames.withLock {
$0[AnySecret(secret)]
}
}
/// Attempts to find an OpenSSH Certificate that corresponds to a ``Secret``
/// - Parameter secret: The secret to search for a certificate with
/// - Returns: A (``Data``, ``Data``) tuple containing the certificate and certificate name, respectively.
private func loadKeyblobAndName<SecretType: Secret>(for secret: SecretType) throws -> (Data, Data)? {
let certificatePath = publicKeyFileStoreController.sshCertificatePath(for: secret)
guard FileManager.default.fileExists(atPath: certificatePath) else {
return nil
}
logger.debug("Found certificate for \(secret.name)")
let certContent = try String(contentsOfFile:certificatePath, encoding: .utf8)
let certElements = certContent.trimmingCharacters(in: .whitespacesAndNewlines).components(separatedBy: " ")
guard certElements.count >= 2 else {
logger.warning("Certificate found for \(secret.name) but failed to load")
throw OpenSSHCertificateError.parsingFailed
}
guard let certDecoded = Data(base64Encoded: certElements[1] as String) else {
logger.warning("Certificate found for \(secret.name) but failed to decode base64 key")
throw OpenSSHCertificateError.parsingFailed
}
if certElements.count >= 3, let certName = certElements[2].data(using: .utf8) {
return (certDecoded, certName)
} else if let certName = secret.name.data(using: .utf8) {
logger.info("Certificate for \(secret.name) does not have a name tag, using secret name instead")
return (certDecoded, certName)
} else {
throw OpenSSHCertificateError.parsingFailed
}
}
}
extension OpenSSHCertificateHandler {
enum OpenSSHCertificateError: LocalizedError {
case unsupportedType
case parsingFailed
case doesNotExist
public var errorDescription: String? {
switch self {
case .unsupportedType:
return "The key type was unsupported"
case .parsingFailed:
return "Failed to properly parse the SSH certificate"
case .doesNotExist:
return "Certificate does not exist"
}
}
}
}

View File

@ -2,7 +2,7 @@ import Foundation
import CryptoKit import CryptoKit
/// Generates OpenSSH representations of Secrets. /// Generates OpenSSH representations of Secrets.
public struct OpenSSHKeyWriter: Sendable { public struct OpenSSHKeyWriter {
/// Initializes the writer. /// Initializes the writer.
public init() { public init() {
@ -64,10 +64,6 @@ extension OpenSSHKeyWriter {
switch algorithm { switch algorithm {
case .ellipticCurve: case .ellipticCurve:
return "ecdsa-sha2-nistp" + String(describing: length) return "ecdsa-sha2-nistp" + String(describing: length)
case .rsa:
// All RSA keys use the same 512 bit hash function, per
// https://security.stackexchange.com/questions/255074/why-are-rsa-sha2-512-and-rsa-sha2-256-supported-but-not-reported-by-ssh-q-key
return "rsa-sha2-512"
} }
} }
@ -80,9 +76,6 @@ extension OpenSSHKeyWriter {
switch algorithm { switch algorithm {
case .ellipticCurve: case .ellipticCurve:
return "nistp" + String(describing: length) return "nistp" + String(describing: length)
case .rsa:
// All RSA keys use the same 512 bit hash function
return "rsa-sha2-512"
} }
} }

View File

@ -1,7 +1,7 @@
import Foundation import Foundation
/// Reads OpenSSH protocol data. /// Reads OpenSSH protocol data.
public final class OpenSSHReader { public class OpenSSHReader {
var remaining: Data var remaining: Data

View File

@ -2,11 +2,10 @@ import Foundation
import OSLog import OSLog
/// Controller responsible for writing public keys to disk, so that they're easily accessible by scripts. /// Controller responsible for writing public keys to disk, so that they're easily accessible by scripts.
public final class PublicKeyFileStoreController: Sendable { public class PublicKeyFileStoreController {
private let logger = Logger(subsystem: "com.maxgoedjen.secretive.secretagent", category: "PublicKeyFileStoreController") private let logger = Logger()
private let directory: String private let directory: String
private let keyWriter = OpenSSHKeyWriter()
/// Initializes a PublicKeyFileStoreController. /// Initializes a PublicKeyFileStoreController.
public init(homeDirectory: String) { public init(homeDirectory: String) {
@ -15,23 +14,16 @@ public final class PublicKeyFileStoreController: Sendable {
/// Writes out the keys specified to disk. /// Writes out the keys specified to disk.
/// - Parameter secrets: The Secrets to generate keys for. /// - Parameter secrets: The Secrets to generate keys for.
/// - Parameter clear: Whether or not any untracked files in the directory should be removed. /// - Parameter clear: Whether or not the directory should be erased before writing keys.
public func generatePublicKeys(for secrets: [AnySecret], clear: Bool = false) throws { public func generatePublicKeys(for secrets: [AnySecret], clear: Bool = false) throws {
logger.log("Writing public keys to disk") logger.log("Writing public keys to disk")
if clear { if clear {
let validPaths = Set(secrets.map { publicKeyPath(for: $0) }).union(Set(secrets.map { sshCertificatePath(for: $0) })) try? FileManager.default.removeItem(at: URL(fileURLWithPath: directory))
let contentsOfDirectory = (try? FileManager.default.contentsOfDirectory(atPath: directory)) ?? []
let fullPathContents = contentsOfDirectory.map { "\(directory)/\($0)" }
let untracked = Set(fullPathContents)
.subtracting(validPaths)
for path in untracked {
try? FileManager.default.removeItem(at: URL(fileURLWithPath: path))
}
} }
try? FileManager.default.createDirectory(at: URL(fileURLWithPath: directory), withIntermediateDirectories: false, attributes: nil) try? FileManager.default.createDirectory(at: URL(fileURLWithPath: directory), withIntermediateDirectories: false, attributes: nil)
let keyWriter = OpenSSHKeyWriter()
for secret in secrets { for secret in secrets {
let path = publicKeyPath(for: secret) let path = path(for: secret)
guard let data = keyWriter.openSSHString(secret: secret).data(using: .utf8) else { continue } guard let data = keyWriter.openSSHString(secret: secret).data(using: .utf8) else { continue }
FileManager.default.createFile(atPath: path, contents: data, attributes: nil) FileManager.default.createFile(atPath: path, contents: data, attributes: nil)
} }
@ -42,30 +34,8 @@ public final class PublicKeyFileStoreController: Sendable {
/// - Parameter secret: The Secret to return the path for. /// - Parameter secret: The Secret to return the path for.
/// - Returns: The path to the Secret's public key. /// - Returns: The path to the Secret's public key.
/// - Warning: This method returning a path does not imply that a key has been written to disk already. This method only describes where it will be written to. /// - Warning: This method returning a path does not imply that a key has been written to disk already. This method only describes where it will be written to.
public func publicKeyPath<SecretType: Secret>(for secret: SecretType) -> String { public func path<SecretType: Secret>(for secret: SecretType) -> String {
let minimalHex = keyWriter.openSSHMD5Fingerprint(secret: secret).replacingOccurrences(of: ":", with: "") directory.appending("/").appending("\(secret.name.replacingOccurrences(of: " ", with: "-")).pub")
return directory.appending("/").appending("\(minimalHex).pub")
}
/// Short-circuit check to ship enumerating a bunch of paths if there's nothing in the cert directory.
public var hasAnyCertificates: Bool {
do {
return try FileManager.default
.contentsOfDirectory(atPath: directory)
.filter { $0.hasSuffix("-cert.pub") }
.isEmpty == false
} catch {
return false
}
}
/// The path for a Secret's SSH Certificate public key.
/// - Parameter secret: The Secret to return the path for.
/// - Returns: The path to the SSH Certificate public key.
/// - Warning: This method returning a path does not imply that a key has a SSH certificates. This method only describes where it will be.
public func sshCertificatePath<SecretType: Secret>(for secret: SecretType) -> String {
let minimalHex = keyWriter.openSSHMD5Fingerprint(secret: secret).replacingOccurrences(of: ":", with: "")
return directory.appending("/").appending("\(minimalHex)-cert.pub")
} }
} }

View File

@ -1,21 +1,14 @@
import Foundation import Foundation
import Observation import Combine
import Synchronization
/// A "Store Store," which holds a list of type-erased stores. /// A "Store Store," which holds a list of type-erased stores.
@Observable public final class SecretStoreList: Sendable { public class SecretStoreList: ObservableObject {
/// The Stores managed by the SecretStoreList. /// The Stores managed by the SecretStoreList.
public var stores: [AnySecretStore] { @Published public var stores: [AnySecretStore] = []
__stores.withLock { $0 }
}
private let __stores: Mutex<[AnySecretStore]> = .init([])
/// A modifiable store, if one is available. /// A modifiable store, if one is available.
public var modifiableStore: AnySecretStoreModifiable? { @Published public var modifiableStore: AnySecretStoreModifiable?
__modifiableStore.withLock { $0 } private var sinks: [AnyCancellable] = []
}
private let __modifiableStore: Mutex<AnySecretStoreModifiable?> = .init(nil)
/// Initializes a SecretStoreList. /// Initializes a SecretStoreList.
public init() { public init() {
@ -23,33 +16,31 @@ import Synchronization
/// Adds a non-type-erased SecretStore to the list. /// Adds a non-type-erased SecretStore to the list.
public func add<SecretStoreType: SecretStore>(store: SecretStoreType) { public func add<SecretStoreType: SecretStore>(store: SecretStoreType) {
__stores.withLock { addInternal(store: AnySecretStore(store))
$0.append(AnySecretStore(store))
}
} }
/// Adds a non-type-erased modifiable SecretStore. /// Adds a non-type-erased modifiable SecretStore.
public func add<SecretStoreType: SecretStoreModifiable>(store: SecretStoreType) { public func add<SecretStoreType: SecretStoreModifiable>(store: SecretStoreType) {
let modifiable = AnySecretStoreModifiable(modifiable: store) let modifiable = AnySecretStoreModifiable(modifiable: store)
__modifiableStore.withLock { modifiableStore = modifiable
$0 = modifiable addInternal(store: modifiable)
}
__stores.withLock {
$0.append(modifiable)
}
} }
/// A boolean describing whether there are any Stores available. /// A boolean describing whether there are any Stores available.
public var anyAvailable: Bool { public var anyAvailable: Bool {
__stores.withLock { stores.reduce(false, { $0 || $1.isAvailable })
$0.reduce(false, { $0 || $1.isAvailable }) }
}
} }
public var allSecrets: [AnySecret] { extension SecretStoreList {
__stores.withLock {
$0.flatMap(\.secrets) private func addInternal(store: AnySecretStore) {
} stores.append(store)
let sink = store.objectWillChange.sink {
self.objectWillChange.send()
}
sinks.append(sink)
} }
} }

View File

@ -1,9 +0,0 @@
import Foundation
/// Protocol describing a persisted authentication context. This is an authorization that can be reused for multiple access to a secret that requires authentication for a specific period of time.
public protocol PersistedAuthenticationContext: Sendable {
/// Whether the context remains valid.
var valid: Bool { get }
/// The date at which the authorization expires and the context becomes invalid.
var expiration: Date { get }
}

View File

@ -1,7 +1,7 @@
import Foundation import Foundation
/// The base protocol for describing a Secret /// The base protocol for describing a Secret
public protocol Secret: Identifiable, Hashable, Sendable { public protocol Secret: Identifiable, Hashable {
/// A user-facing string identifying the Secret. /// A user-facing string identifying the Secret.
var name: String { get } var name: String { get }
@ -9,18 +9,15 @@ public protocol Secret: Identifiable, Hashable, Sendable {
var algorithm: Algorithm { get } var algorithm: Algorithm { get }
/// The key size for the secret. /// The key size for the secret.
var keySize: Int { get } var keySize: Int { get }
/// Whether the secret requires authentication before use.
var requiresAuthentication: Bool { get }
/// The public key data for the secret. /// The public key data for the secret.
var publicKey: Data { get } var publicKey: Data { get }
} }
/// The type of algorithm the Secret uses. Currently, only elliptic curve algorithms are supported. /// The type of algorithm the Secret uses. Currently, only elliptic curve algorithms are supported.
public enum Algorithm: Hashable, Sendable { public enum Algorithm: Hashable {
case ellipticCurve case ellipticCurve
case rsa
/// Initializes the Algorithm with a secAttr representation of an algorithm. /// Initializes the Algorithm with a secAttr representation of an algorithm.
/// - Parameter secAttr: the secAttr, represented as an NSNumber. /// - Parameter secAttr: the secAttr, represented as an NSNumber.
@ -29,19 +26,8 @@ public enum Algorithm: Hashable, Sendable {
switch secAttrString { switch secAttrString {
case kSecAttrKeyTypeEC: case kSecAttrKeyTypeEC:
self = .ellipticCurve self = .ellipticCurve
case kSecAttrKeyTypeRSA:
self = .rsa
default: default:
fatalError() fatalError()
} }
} }
public var secAttrKeyType: CFString {
switch self {
case .ellipticCurve:
return kSecAttrKeyTypeEC
case .rsa:
return kSecAttrKeyTypeRSA
}
}
} }

View File

@ -2,7 +2,7 @@ import Foundation
import Combine import Combine
/// Manages access to Secrets, and performs signature operations on data using those Secrets. /// Manages access to Secrets, and performs signature operations on data using those Secrets.
public protocol SecretStore: Identifiable, Sendable { public protocol SecretStore: ObservableObject, Identifiable {
associatedtype SecretType: Secret associatedtype SecretType: Secret
@ -20,32 +20,15 @@ public protocol SecretStore: Identifiable, Sendable {
/// - data: The data to sign. /// - data: The data to sign.
/// - secret: The ``Secret`` to sign with. /// - secret: The ``Secret`` to sign with.
/// - provenance: A ``SigningRequestProvenance`` describing where the request came from. /// - provenance: A ``SigningRequestProvenance`` describing where the request came from.
/// - Returns: The signed data. /// - Returns: A ``SignedData`` object, containing the signature and metadata about the signature process.
func sign(data: Data, with secret: SecretType, for provenance: SigningRequestProvenance) async throws -> Data func sign(data: Data, with secret: SecretType, for provenance: SigningRequestProvenance) throws -> SignedData
/// Verifies that a signature is valid over a specified payload.
/// - Parameters:
/// - signature: The signature over the data.
/// - data: The data to verify the signature of.
/// - secret: The secret whose signature to verify.
/// - Returns: Whether the signature was verified.
func verify(signature: Data, for data: Data, with secret: SecretType) async throws -> Bool
/// Checks to see if there is currently a valid persisted authentication for a given secret.
/// - Parameters:
/// - secret: The ``Secret`` to check if there is a persisted authentication for.
/// - Returns: A persisted authentication context, if a valid one exists.
func existingPersistedAuthenticationContext(secret: SecretType) async -> PersistedAuthenticationContext?
/// Persists user authorization for access to a secret. /// Persists user authorization for access to a secret.
/// - Parameters: /// - Parameters:
/// - secret: The ``Secret`` to persist the authorization for. /// - secret: The ``Secret`` to persist the authorization for.
/// - duration: The duration that the authorization should persist for. /// - duration: The duration that the authorization should persist for.
/// - Note: This is used for temporarily unlocking access to a secret which would otherwise require authentication every single use. This is useful for situations where the user anticipates several rapid accesses to a authorization-guarded secret. /// - Note: This is used for temporarily unlocking access to a secret which would otherwise require authentication every single use. This is useful for situations where the user anticipates several rapid accesses to a authorization-guarded secret.
func persistAuthentication(secret: SecretType, forDuration duration: TimeInterval) async throws func persistAuthentication(secret: SecretType, forDuration duration: TimeInterval) throws
/// Requests that the store reload secrets from any backing store, if neccessary.
func reloadSecrets() async
} }
@ -56,26 +39,23 @@ public protocol SecretStoreModifiable: SecretStore {
/// - Parameters: /// - Parameters:
/// - name: The user-facing name for the ``Secret``. /// - name: The user-facing name for the ``Secret``.
/// - requiresAuthentication: A boolean indicating whether or not the user will be required to authenticate before performing signature operations with the secret. /// - requiresAuthentication: A boolean indicating whether or not the user will be required to authenticate before performing signature operations with the secret.
func create(name: String, requiresAuthentication: Bool) async throws func create(name: String, requiresAuthentication: Bool) throws
/// Deletes a Secret in the store. /// Deletes a Secret in the store.
/// - Parameters: /// - Parameters:
/// - secret: The ``Secret`` to delete. /// - secret: The ``Secret`` to delete.
func delete(secret: SecretType) async throws func delete(secret: SecretType) throws
/// Updates the name of a Secret in the store. /// Updates the name of a Secret in the store.
/// - Parameters: /// - Parameters:
/// - secret: The ``Secret`` to update. /// - secret: The ``Secret`` to update.
/// - name: The new name for the Secret. /// - name: The new name for the Secret.
func update(secret: SecretType, name: String) async throws func update(secret: SecretType, name: String) throws
} }
extension NSNotification.Name { extension NSNotification.Name {
// Distributed notification that keys were modified out of process (ie, that the management tool added/removed secrets)
public static let secretStoreUpdated = NSNotification.Name("com.maxgoedjen.Secretive.secretStore.updated") public static let secretStoreUpdated = NSNotification.Name("com.maxgoedjen.Secretive.secretStore.updated")
// Internal notification that keys were reloaded from the backing store.
public static let secretStoreReloaded = NSNotification.Name("com.maxgoedjen.Secretive.secretStore.reloaded")
} }

View File

@ -0,0 +1,20 @@
import Foundation
/// Describes the output of a sign request.
public struct SignedData {
/// The signed data.
public let data: Data
/// A boolean describing whether authentication was required during the signature process.
public let requiredAuthentication: Bool
/// Initializes a new SignedData.
/// - Parameters:
/// - data: The signed data.
/// - requiredAuthentication: A boolean describing whether authentication was required during the signature process.
public init(data: Data, requiredAuthentication: Bool) {
self.data = data
self.requiredAuthentication = requiredAuthentication
}
}

View File

@ -11,7 +11,6 @@ extension SecureEnclave {
public let name: String public let name: String
public let algorithm = Algorithm.ellipticCurve public let algorithm = Algorithm.ellipticCurve
public let keySize = 256 public let keySize = 256
public let requiresAuthentication: Bool
public let publicKey: Data public let publicKey: Data
} }

View File

@ -1,41 +1,37 @@
import Foundation import Foundation
import Observation
import Security import Security
import CryptoKit import CryptoTokenKit
import LocalAuthentication import LocalAuthentication
import SecretKit import SecretKit
import Synchronization
extension SecureEnclave { extension SecureEnclave {
/// An implementation of Store backed by the Secure Enclave. /// An implementation of Store backed by the Secure Enclave.
@Observable public final class Store: SecretStoreModifiable { public class Store: SecretStoreModifiable {
public var isAvailable: Bool { public var isAvailable: Bool {
CryptoKit.SecureEnclave.isAvailable // For some reason, as of build time, CryptoKit.SecureEnclave.isAvailable always returns false
// error msg "Received error sending GET UNIQUE DEVICE command"
// Verify it with TKTokenWatcher manually.
TKTokenWatcher().tokenIDs.contains("com.apple.setoken")
} }
public let id = UUID() public let id = UUID()
public let name = String(localized: "secure_enclave") public let name = NSLocalizedString("Secure Enclave", comment: "Secure Enclave")
public var secrets: [Secret] { @Published public private(set) var secrets: [Secret] = []
_secrets.withLock { $0 }
}
private let _secrets: Mutex<[Secret]> = .init([])
private let persistedAuthenticationContexts: Mutex<[Secret: PersistentAuthenticationContext]> = .init([:]) private var persistedAuthenticationContexts: [Secret: PersistentAuthenticationContext] = [:]
/// Initializes a Store. /// Initializes a Store.
public init() { public init() {
Task { DistributedNotificationCenter.default().addObserver(forName: .secretStoreUpdated, object: nil, queue: .main) { _ in
for await _ in DistributedNotificationCenter.default().notifications(named: .secretStoreUpdated) { self.reloadSecrets(notify: false)
await reloadSecretsInternal(notifyAgent: false)
}
} }
loadSecrets() loadSecrets()
} }
// MARK: Public API // MARK: Public API
public func create(name: String, requiresAuthentication: Bool) async throws { public func create(name: String, requiresAuthentication: Bool) throws {
var accessError: SecurityError? var accessError: SecurityError?
let flags: SecAccessControlCreateFlags let flags: SecAccessControlCreateFlags
if requiresAuthentication { if requiresAuthentication {
@ -52,7 +48,7 @@ extension SecureEnclave {
throw error.takeRetainedValue() as Error throw error.takeRetainedValue() as Error
} }
let attributes = KeychainDictionary([ let attributes = [
kSecAttrLabel: name, kSecAttrLabel: name,
kSecAttrKeyType: Constants.keyType, kSecAttrKeyType: Constants.keyType,
kSecAttrTokenID: kSecAttrTokenIDSecureEnclave, kSecAttrTokenID: kSecAttrTokenIDSecureEnclave,
@ -61,7 +57,7 @@ extension SecureEnclave {
kSecAttrIsPermanent: true, kSecAttrIsPermanent: true,
kSecAttrAccessControl: access kSecAttrAccessControl: access
] ]
]) ] as CFDictionary
var createKeyError: SecurityError? var createKeyError: SecurityError?
let keypair = SecKeyCreateRandomKey(attributes, &createKeyError) let keypair = SecKeyCreateRandomKey(attributes, &createKeyError)
@ -72,82 +68,49 @@ extension SecureEnclave {
throw KeychainError(statusCode: nil) throw KeychainError(statusCode: nil)
} }
try savePublicKey(publicKey, name: name) try savePublicKey(publicKey, name: name)
await reloadSecretsInternal() reloadSecrets()
} }
public func delete(secret: Secret) async throws { public func delete(secret: Secret) throws {
let deleteAttributes = KeychainDictionary([ let deleteAttributes = [
kSecClass: kSecClassKey, kSecClass: kSecClassKey,
kSecAttrApplicationLabel: secret.id as CFData kSecAttrApplicationLabel: secret.id as CFData
]) ] as CFDictionary
let status = SecItemDelete(deleteAttributes) let status = SecItemDelete(deleteAttributes)
if status != errSecSuccess { if status != errSecSuccess {
throw KeychainError(statusCode: status) throw KeychainError(statusCode: status)
} }
await reloadSecretsInternal() reloadSecrets()
} }
public func update(secret: Secret, name: String) async throws { public func update(secret: Secret, name: String) throws {
let updateQuery = KeychainDictionary([ let updateQuery = [
kSecClass: kSecClassKey, kSecClass: kSecClassKey,
kSecAttrApplicationLabel: secret.id as CFData kSecAttrApplicationLabel: secret.id as CFData
]) ] as CFDictionary
let updatedAttributes = KeychainDictionary([ let updatedAttributes = [
kSecAttrLabel: name, kSecAttrLabel: name,
]) ] as CFDictionary
let status = SecItemUpdate(updateQuery, updatedAttributes) let status = SecItemUpdate(updateQuery, updatedAttributes)
if status != errSecSuccess { if status != errSecSuccess {
throw KeychainError(statusCode: status) throw KeychainError(statusCode: status)
} }
await reloadSecretsInternal() reloadSecrets()
} }
public func sign(data: Data, with secret: Secret, for provenance: SigningRequestProvenance) throws -> Data { public func sign(data: Data, with secret: SecretType, for provenance: SigningRequestProvenance) throws -> SignedData {
let context: Mutex<LAContext> let context: LAContext
// if let existing = persistedAuthenticationContexts.withLock({ $0 })[secret], existing.valid { if let existing = persistedAuthenticationContexts[secret], existing.valid {
// context = existing.context context = existing.context
// } else { } else {
let newContext = LAContext() let newContext = LAContext()
newContext.localizedCancelTitle = String(localized: "auth_context_request_deny_button") newContext.localizedCancelTitle = "Deny"
context = .init(newContext) context = newContext
// }
return try context.withLock { context in
context.localizedReason = String(localized: "auth_context_request_signature_description_\(provenance.origin.displayName)_\(secret.name)")
let attributes = KeychainDictionary([
kSecClass: kSecClassKey,
kSecAttrKeyClass: kSecAttrKeyClassPrivate,
kSecAttrApplicationLabel: secret.id as CFData,
kSecAttrKeyType: Constants.keyType,
kSecAttrTokenID: kSecAttrTokenIDSecureEnclave,
kSecAttrApplicationTag: Constants.keyTag,
kSecUseAuthenticationContext: context,
kSecReturnRef: true
])
var untyped: CFTypeRef?
let status = SecItemCopyMatching(attributes, &untyped)
if status != errSecSuccess {
throw KeychainError(statusCode: status)
}
guard let untypedSafe = untyped else {
throw KeychainError(statusCode: errSecSuccess)
}
let key = untypedSafe as! SecKey
var signError: SecurityError?
guard let signature = SecKeyCreateSignature(key, .ecdsaSignatureMessageX962SHA256, data as CFData, &signError) else {
throw SigningError(error: signError)
}
return signature as Data
} }
} context.localizedReason = "sign a request from \"\(provenance.origin.displayName)\" using secret \"\(secret.name)\""
let attributes = [
public func verify(signature: Data, for data: Data, with secret: Secret) throws -> Bool {
let context = LAContext()
context.localizedReason = String(localized: "auth_context_request_verify_description_\(secret.name)")
context.localizedCancelTitle = String(localized: "auth_context_request_deny_button")
let attributes = KeychainDictionary([
kSecClass: kSecClassKey, kSecClass: kSecClassKey,
kSecAttrKeyClass: kSecAttrKeyClassPrivate, kSecAttrKeyClass: kSecAttrKeyClassPrivate,
kSecAttrApplicationLabel: secret.id as CFData, kSecAttrApplicationLabel: secret.id as CFData,
@ -156,8 +119,7 @@ extension SecureEnclave {
kSecAttrApplicationTag: Constants.keyTag, kSecAttrApplicationTag: Constants.keyTag,
kSecUseAuthenticationContext: context, kSecUseAuthenticationContext: context,
kSecReturnRef: true kSecReturnRef: true
]) ] as CFDictionary
var verifyError: SecurityError?
var untyped: CFTypeRef? var untyped: CFTypeRef?
let status = SecItemCopyMatching(attributes, &untyped) let status = SecItemCopyMatching(attributes, &untyped)
if status != errSecSuccess { if status != errSecSuccess {
@ -167,49 +129,41 @@ extension SecureEnclave {
throw KeychainError(statusCode: errSecSuccess) throw KeychainError(statusCode: errSecSuccess)
} }
let key = untypedSafe as! SecKey let key = untypedSafe as! SecKey
let verified = SecKeyVerifySignature(key, .ecdsaSignatureMessageX962SHA256, data as CFData, signature as CFData, &verifyError) var signError: SecurityError?
if !verified, let verifyError {
if verifyError.takeUnretainedValue() ~= .verifyError {
return false
} else {
throw SigningError(error: verifyError)
}
}
return verified
}
public func existingPersistedAuthenticationContext(secret: Secret) -> PersistedAuthenticationContext? { let signingStartTime = Date()
guard let persisted = persistedAuthenticationContexts.withLock({ $0 })[secret], persisted.valid else { return nil } guard let signature = SecKeyCreateSignature(key, .ecdsaSignatureMessageX962SHA256, data as CFData, &signError) else {
return persisted throw SigningError(error: signError)
}
let signatureDuration = Date().timeIntervalSince(signingStartTime)
// Hack to determine if the user had to authenticate to sign.
// Since there's now way to inspect SecAccessControl to determine (afaict).
let requiredAuthentication = signatureDuration > Constants.unauthenticatedThreshold
return SignedData(data: signature as Data, requiredAuthentication: requiredAuthentication)
} }
public func persistAuthentication(secret: Secret, forDuration duration: TimeInterval) throws { public func persistAuthentication(secret: Secret, forDuration duration: TimeInterval) throws {
let newContext = LAContext() let newContext = LAContext()
newContext.touchIDAuthenticationAllowableReuseDuration = duration newContext.touchIDAuthenticationAllowableReuseDuration = duration
newContext.localizedCancelTitle = String(localized: "auth_context_request_deny_button") newContext.localizedCancelTitle = "Deny"
let formatter = DateComponentsFormatter() let formatter = DateComponentsFormatter()
formatter.unitsStyle = .spellOut formatter.unitsStyle = .spellOut
formatter.allowedUnits = [.hour, .minute, .day] formatter.allowedUnits = [.hour, .minute, .day]
if let durationString = formatter.string(from: duration) { if let durationString = formatter.string(from: duration) {
newContext.localizedReason = String(localized: "auth_context_persist_for_duration_\(secret.name)_\(durationString)") newContext.localizedReason = "unlock secret \"\(secret.name)\" for \(durationString)"
} else { } else {
newContext.localizedReason = String(localized: "auth_context_persist_for_duration_unknown_\(secret.name)") newContext.localizedReason = "unlock secret \"\(secret.name)\""
} }
newContext.evaluatePolicy(LAPolicy.deviceOwnerAuthentication, localizedReason: newContext.localizedReason) { [weak self] success, _ in newContext.evaluatePolicy(LAPolicy.deviceOwnerAuthentication, localizedReason: newContext.localizedReason) { [weak self] success, _ in
guard success, let self else { return } guard success else { return }
let context = PersistentAuthenticationContext(secret: secret, context: newContext, duration: duration) let context = PersistentAuthenticationContext(secret: secret, context: newContext, duration: duration)
self.persistedAuthenticationContexts.withLock { self?.persistedAuthenticationContexts[secret] = context
$0[secret] = context
}
} }
} }
public func reloadSecrets() async {
await reloadSecretsInternal(notifyAgent: false)
}
} }
} }
@ -217,24 +171,18 @@ extension SecureEnclave {
extension SecureEnclave.Store { extension SecureEnclave.Store {
/// Reloads all secrets from the store. /// Reloads all secrets from the store.
/// - Parameter notifyAgent: A boolean indicating whether a distributed notification should be posted, notifying other processes (ie, the SecretAgent) to reload their stores as well. /// - Parameter notify: A boolean indicating whether a distributed notification should be posted, notifying other processes (ie, the SecretAgent) to reload their stores as well.
private func reloadSecretsInternal(notifyAgent: Bool = true) async { private func reloadSecrets(notify: Bool = true) {
let before = secrets secrets.removeAll()
_secrets.withLock {
$0.removeAll()
}
loadSecrets() loadSecrets()
if secrets != before { if notify {
NotificationCenter.default.post(name: .secretStoreReloaded, object: self) DistributedNotificationCenter.default().post(name: .secretStoreUpdated, object: nil)
if notifyAgent {
DistributedNotificationCenter.default().postNotificationName(.secretStoreUpdated, object: nil, deliverImmediately: true)
}
} }
} }
/// Loads all secrets from the store. /// Loads all secrets from the store.
private func loadSecrets() { private func loadSecrets() {
let publicAttributes = KeychainDictionary([ let attributes = [
kSecClass: kSecClassKey, kSecClass: kSecClassKey,
kSecAttrKeyType: SecureEnclave.Constants.keyType, kSecAttrKeyType: SecureEnclave.Constants.keyType,
kSecAttrApplicationTag: SecureEnclave.Constants.keyTag, kSecAttrApplicationTag: SecureEnclave.Constants.keyTag,
@ -242,51 +190,19 @@ extension SecureEnclave.Store {
kSecReturnRef: true, kSecReturnRef: true,
kSecMatchLimit: kSecMatchLimitAll, kSecMatchLimit: kSecMatchLimitAll,
kSecReturnAttributes: true kSecReturnAttributes: true
]) ] as CFDictionary
var publicUntyped: CFTypeRef? var untyped: CFTypeRef?
SecItemCopyMatching(publicAttributes, &publicUntyped) SecItemCopyMatching(attributes, &untyped)
guard let publicTyped = publicUntyped as? [[CFString: Any]] else { return } guard let typed = untyped as? [[CFString: Any]] else { return }
let privateAttributes = KeychainDictionary([ let wrapped: [SecureEnclave.Secret] = typed.map {
kSecClass: kSecClassKey, let name = $0[kSecAttrLabel] as? String ?? "Unnamed"
kSecAttrKeyType: SecureEnclave.Constants.keyType,
kSecAttrApplicationTag: SecureEnclave.Constants.keyTag,
kSecAttrKeyClass: kSecAttrKeyClassPrivate,
kSecReturnRef: true,
kSecMatchLimit: kSecMatchLimitAll,
kSecReturnAttributes: true
])
var privateUntyped: CFTypeRef?
SecItemCopyMatching(privateAttributes, &privateUntyped)
guard let privateTyped = privateUntyped as? [[CFString: Any]] else { return }
let privateMapped = privateTyped.reduce(into: [:] as [Data: [CFString: Any]]) { partialResult, next in
let id = next[kSecAttrApplicationLabel] as! Data
partialResult[id] = next
}
let authNotRequiredAccessControl: SecAccessControl =
SecAccessControlCreateWithFlags(kCFAllocatorDefault,
kSecAttrAccessibleWhenUnlockedThisDeviceOnly,
[.privateKeyUsage],
nil)!
let wrapped: [SecureEnclave.Secret] = publicTyped.map {
let name = $0[kSecAttrLabel] as? String ?? String(localized: "unnamed_secret")
let id = $0[kSecAttrApplicationLabel] as! Data let id = $0[kSecAttrApplicationLabel] as! Data
let publicKeyRef = $0[kSecValueRef] as! SecKey let publicKeyRef = $0[kSecValueRef] as! SecKey
let publicKeyAttributes = SecKeyCopyAttributes(publicKeyRef) as! [CFString: Any] let publicKeyAttributes = SecKeyCopyAttributes(publicKeyRef) as! [CFString: Any]
let publicKey = publicKeyAttributes[kSecValueData] as! Data let publicKey = publicKeyAttributes[kSecValueData] as! Data
let privateKey = privateMapped[id] return SecureEnclave.Secret(id: id, name: name, publicKey: publicKey)
let requiresAuth: Bool
if let authRequirements = privateKey?[kSecAttrAccessControl] {
// Unfortunately we can't inspect the access control object directly, but it does behave predicatable with equality.
requiresAuth = authRequirements as! SecAccessControl != authNotRequiredAccessControl
} else {
requiresAuth = false
}
return SecureEnclave.Secret(id: id, name: name, requiresAuthentication: requiresAuth, publicKey: publicKey)
}
_secrets.withLock {
$0.append(contentsOf: wrapped)
} }
secrets.append(contentsOf: wrapped)
} }
/// Saves a public key. /// Saves a public key.
@ -294,7 +210,7 @@ extension SecureEnclave.Store {
/// - publicKey: The public key to save. /// - publicKey: The public key to save.
/// - name: A user-facing name for the key. /// - name: A user-facing name for the key.
private func savePublicKey(_ publicKey: SecKey, name: String) throws { private func savePublicKey(_ publicKey: SecKey, name: String) throws {
let attributes = KeychainDictionary([ let attributes = [
kSecClass: kSecClassKey, kSecClass: kSecClassKey,
kSecAttrKeyType: SecureEnclave.Constants.keyType, kSecAttrKeyType: SecureEnclave.Constants.keyType,
kSecAttrKeyClass: kSecAttrKeyClassPublic, kSecAttrKeyClass: kSecAttrKeyClassPublic,
@ -303,20 +219,42 @@ extension SecureEnclave.Store {
kSecAttrIsPermanent: true, kSecAttrIsPermanent: true,
kSecReturnData: true, kSecReturnData: true,
kSecAttrLabel: name kSecAttrLabel: name
]) ] as CFDictionary
let status = SecItemAdd(attributes, nil) let status = SecItemAdd(attributes, nil)
if status != errSecSuccess { if status != errSecSuccess {
throw KeychainError(statusCode: status) throw SecureEnclave.KeychainError(statusCode: status)
} }
} }
} }
extension SecureEnclave {
/// A wrapper around an error code reported by a Keychain API.
public struct KeychainError: Error {
/// The status code involved, if one was reported.
public let statusCode: OSStatus?
}
/// A signing-related error.
public struct SigningError: Error {
/// The underlying error reported by the API, if one was returned.
public let error: SecurityError?
}
}
extension SecureEnclave {
public typealias SecurityError = Unmanaged<CFError>
}
extension SecureEnclave { extension SecureEnclave {
enum Constants { enum Constants {
static let keyTag = Data("com.maxgoedjen.secretive.secureenclave.key".utf8) static let keyTag = "com.maxgoedjen.secretive.secureenclave.key".data(using: .utf8)! as CFData
static let keyType = kSecAttrKeyTypeECSECPrimeRandom as String static let keyType = kSecAttrKeyTypeECSECPrimeRandom
static let unauthenticatedThreshold: TimeInterval = 0.05 static let unauthenticatedThreshold: TimeInterval = 0.05
} }
@ -325,15 +263,15 @@ extension SecureEnclave {
extension SecureEnclave { extension SecureEnclave {
/// A context describing a persisted authentication. /// A context describing a persisted authentication.
private final class PersistentAuthenticationContext: PersistedAuthenticationContext { private struct PersistentAuthenticationContext {
/// The Secret to persist authentication for. /// The Secret to persist authentication for.
let secret: Secret let secret: Secret
/// The LAContext used to authorize the persistent context. /// The LAContext used to authorize the persistent context.
nonisolated(unsafe) let context: LAContext let context: LAContext
/// An expiration date for the context. /// An expiration date for the context.
/// - Note - Monotonic time instead of Date() to prevent people setting the clock back. /// - Note - Monotonic time instead of Date() to prevent people setting the clock back.
let monotonicExpiration: UInt64 let expiration: UInt64
/// Initializes a context. /// Initializes a context.
/// - Parameters: /// - Parameters:
@ -344,18 +282,12 @@ extension SecureEnclave {
self.secret = secret self.secret = secret
self.context = context self.context = context
let durationInNanoSeconds = Measurement(value: duration, unit: UnitDuration.seconds).converted(to: .nanoseconds).value let durationInNanoSeconds = Measurement(value: duration, unit: UnitDuration.seconds).converted(to: .nanoseconds).value
self.monotonicExpiration = clock_gettime_nsec_np(CLOCK_MONOTONIC) + UInt64(durationInNanoSeconds) self.expiration = clock_gettime_nsec_np(CLOCK_MONOTONIC) + UInt64(durationInNanoSeconds)
} }
/// A boolean describing whether or not the context is still valid. /// A boolean describing whether or not the context is still valid.
var valid: Bool { var valid: Bool {
clock_gettime_nsec_np(CLOCK_MONOTONIC) < monotonicExpiration clock_gettime_nsec_np(CLOCK_MONOTONIC) < expiration
}
var expiration: Date {
let remainingNanoseconds = monotonicExpiration - clock_gettime_nsec_np(CLOCK_MONOTONIC)
let remainingInSeconds = Measurement(value: Double(remainingNanoseconds), unit: UnitDuration.nanoseconds).converted(to: .seconds).value
return Date(timeIntervalSinceNow: remainingInSeconds)
} }
} }

View File

@ -6,3 +6,9 @@
- ``Secret`` - ``Secret``
- ``Store`` - ``Store``
### Errors
- ``KeychainError``
- ``SigningError``
- ``SecurityError``

View File

@ -11,7 +11,6 @@ extension SmartCard {
public let name: String public let name: String
public let algorithm: Algorithm public let algorithm: Algorithm
public let keySize: Int public let keySize: Int
public let requiresAuthentication: Bool = false
public let publicKey: Data public let publicKey: Data
} }

View File

@ -1,6 +1,4 @@
import Foundation import Foundation
import Synchronization
import Observation
import Security import Security
import CryptoTokenKit import CryptoTokenKit
import LocalAuthentication import LocalAuthentication
@ -8,44 +6,30 @@ import SecretKit
extension SmartCard { extension SmartCard {
private struct State {
var isAvailable = false
var name = String(localized: "smart_card")
var secrets: [Secret] = []
let watcher = TKTokenWatcher()
var tokenID: String? = nil
}
/// An implementation of Store backed by a Smart Card. /// An implementation of Store backed by a Smart Card.
@Observable public final class Store: SecretStore { public class Store: SecretStore {
private let state: Mutex<State> = .init(.init())
public var isAvailable: Bool {
state.withLock { $0.isAvailable }
}
@Published public var isAvailable: Bool = false
public let id = UUID() public let id = UUID()
public var name: String { public private(set) var name = NSLocalizedString("Smart Card", comment: "Smart Card")
state.withLock { $0.name } @Published public private(set) var secrets: [Secret] = []
} private let watcher = TKTokenWatcher()
public var secrets: [Secret] { private var tokenID: String?
state.withLock { $0.secrets }
}
/// Initializes a Store. /// Initializes a Store.
public init() { public init() {
state.withLock { state in tokenID = watcher.nonSecureEnclaveTokens.first
if let tokenID = state.tokenID { watcher.setInsertionHandler { string in
state.isAvailable = true guard self.tokenID == nil else { return }
state.watcher.addRemovalHandler(self.smartcardRemoved, forTokenID: tokenID) guard !string.contains("setoken") else { return }
}
state.watcher.setInsertionHandler { id in self.tokenID = string
// Setting insertion handler will cause it to be called immediately. self.reloadSecrets()
// Make a thread jump so we don't hit a recursive lock attempt. self.watcher.addRemovalHandler(self.smartcardRemoved, forTokenID: string)
Task { }
self.smartcardInserted(for: id) if let tokenID = tokenID {
} self.isAvailable = true
} self.watcher.addRemovalHandler(self.smartcardRemoved, forTokenID: tokenID)
} }
loadSecrets() loadSecrets()
} }
@ -60,19 +44,19 @@ extension SmartCard {
fatalError("Keys must be deleted on the smart card.") fatalError("Keys must be deleted on the smart card.")
} }
public func sign(data: Data, with secret: Secret, for provenance: SigningRequestProvenance) throws -> Data { public func sign(data: Data, with secret: SecretType, for provenance: SigningRequestProvenance) throws -> SignedData {
guard let tokenID = state.withLock({ $0.tokenID }) else { fatalError() } guard let tokenID = tokenID else { fatalError() }
let context = LAContext() let context = LAContext()
context.localizedReason = String(localized: "auth_context_request_signature_description_\(provenance.origin.displayName)_\(secret.name)") context.localizedReason = "sign a request from \"\(provenance.origin.displayName)\" using secret \"\(secret.name)\""
context.localizedCancelTitle = String(localized: "auth_context_request_deny_button") context.localizedCancelTitle = "Deny"
let attributes = KeychainDictionary([ let attributes = [
kSecClass: kSecClassKey, kSecClass: kSecClassKey,
kSecAttrKeyClass: kSecAttrKeyClassPrivate, kSecAttrKeyClass: kSecAttrKeyClassPrivate,
kSecAttrApplicationLabel: secret.id as CFData, kSecAttrApplicationLabel: secret.id as CFData,
kSecAttrTokenID: tokenID, kSecAttrTokenID: tokenID,
kSecUseAuthenticationContext: context, kSecUseAuthenticationContext: context,
kSecReturnRef: true kSecReturnRef: true
]) ] as CFDictionary
var untyped: CFTypeRef? var untyped: CFTypeRef?
let status = SecItemCopyMatching(attributes, &untyped) let status = SecItemCopyMatching(attributes, &untyped)
if status != errSecSuccess { if status != errSecSuccess {
@ -83,45 +67,22 @@ extension SmartCard {
} }
let key = untypedSafe as! SecKey let key = untypedSafe as! SecKey
var signError: SecurityError? var signError: SecurityError?
guard let signature = SecKeyCreateSignature(key, signatureAlgorithm(for: secret, allowRSA: true), data as CFData, &signError) else { let signatureAlgorithm: SecKeyAlgorithm
switch (secret.algorithm, secret.keySize) {
case (.ellipticCurve, 256):
signatureAlgorithm = .ecdsaSignatureMessageX962SHA256
case (.ellipticCurve, 384):
signatureAlgorithm = .ecdsaSignatureMessageX962SHA384
default:
fatalError()
}
guard let signature = SecKeyCreateSignature(key, signatureAlgorithm, data as CFData, &signError) else {
throw SigningError(error: signError) throw SigningError(error: signError)
} }
return signature as Data return SignedData(data: signature as Data, requiredAuthentication: false)
} }
public func verify(signature: Data, for data: Data, with secret: Secret) throws -> Bool { public func persistAuthentication(secret: SmartCard.Secret, forDuration: TimeInterval) throws {
let attributes = KeychainDictionary([
kSecAttrKeyType: secret.algorithm.secAttrKeyType,
kSecAttrKeySizeInBits: secret.keySize,
kSecAttrKeyClass: kSecAttrKeyClassPublic
])
var verifyError: SecurityError?
let untyped: CFTypeRef? = SecKeyCreateWithData(secret.publicKey as CFData, attributes, &verifyError)
guard let untypedSafe = untyped else {
throw KeychainError(statusCode: errSecSuccess)
}
let key = untypedSafe as! SecKey
let verified = SecKeyVerifySignature(key, signatureAlgorithm(for: secret, allowRSA: true), data as CFData, signature as CFData, &verifyError)
if !verified, let verifyError {
if verifyError.takeUnretainedValue() ~= .verifyError {
return false
} else {
throw SigningError(error: verifyError)
}
}
return verified
}
public func existingPersistedAuthenticationContext(secret: Secret) -> PersistedAuthenticationContext? {
nil
}
public func persistAuthentication(secret: Secret, forDuration: TimeInterval) throws {
}
/// Reloads all secrets from the store.
public func reloadSecrets() {
reloadSecretsInternal()
} }
} }
@ -130,66 +91,56 @@ extension SmartCard {
extension SmartCard.Store { extension SmartCard.Store {
private func reloadSecretsInternal() {
let before = state.withLock {
$0.isAvailable = $0.tokenID != nil
let before = $0.secrets
$0.secrets.removeAll()
return before
}
self.loadSecrets()
if self.secrets != before {
NotificationCenter.default.post(name: .secretStoreReloaded, object: self)
}
}
/// Resets the token ID and reloads secrets.
/// - Parameter tokenID: The ID of the token that was inserted.
private func smartcardInserted(for tokenID: String? = nil) {
state.withLock { state in
guard let string = state.watcher.nonSecureEnclaveTokens.first else { return }
guard state.tokenID == nil else { return }
guard !string.contains("setoken") else { return }
state.tokenID = string
state.watcher.addRemovalHandler(self.smartcardRemoved, forTokenID: string)
state.tokenID = string
}
}
/// Resets the token ID and reloads secrets. /// Resets the token ID and reloads secrets.
/// - Parameter tokenID: The ID of the token that was removed. /// - Parameter tokenID: The ID of the token that was removed.
private func smartcardRemoved(for tokenID: String? = nil) { private func smartcardRemoved(for tokenID: String? = nil) {
state.withLock { self.tokenID = nil
$0.tokenID = nil
}
reloadSecrets() reloadSecrets()
} }
/// Reloads all secrets from the store.
private func reloadSecrets() {
DispatchQueue.main.async {
self.isAvailable = self.tokenID != nil
self.secrets.removeAll()
self.loadSecrets()
}
}
/// Loads all secrets from the store. /// Loads all secrets from the store.
private func loadSecrets() { private func loadSecrets() {
guard let tokenID = state.withLock({ $0.tokenID }) else { return } guard let tokenID = tokenID else { return }
let fallbackName = String(localized: "smart_card") let fallbackName = NSLocalizedString("Smart Card", comment: "Smart Card")
state.withLock { if #available(macOS 12.0, *) {
if let driverName = $0.watcher.tokenInfo(forTokenID: tokenID)?.driverName { if let driverName = watcher.tokenInfo(forTokenID: tokenID)?.driverName {
$0.name = driverName name = driverName
} else { } else {
$0.name = fallbackName name = fallbackName
}
} else {
// Hack to read name if there's only one smart card
let slotNames = TKSmartCardSlotManager().slotNames
if watcher.nonSecureEnclaveTokens.count == 1 && slotNames.count == 1 {
name = slotNames.first!
} else {
name = fallbackName
} }
} }
let attributes = KeychainDictionary([ let attributes = [
kSecClass: kSecClassKey, kSecClass: kSecClassKey,
kSecAttrTokenID: tokenID, kSecAttrTokenID: tokenID,
kSecAttrKeyType: kSecAttrKeyTypeEC, // Restrict to EC
kSecReturnRef: true, kSecReturnRef: true,
kSecMatchLimit: kSecMatchLimitAll, kSecMatchLimit: kSecMatchLimitAll,
kSecReturnAttributes: true kSecReturnAttributes: true
]) ] as CFDictionary
var untyped: CFTypeRef? var untyped: CFTypeRef?
SecItemCopyMatching(attributes, &untyped) SecItemCopyMatching(attributes, &untyped)
guard let typed = untyped as? [[CFString: Any]] else { return } guard let typed = untyped as? [[CFString: Any]] else { return }
let wrapped = typed.map { let wrapped: [SmartCard.Secret] = typed.map {
let name = $0[kSecAttrLabel] as? String ?? String(localized: "unnamed_secret") let name = $0[kSecAttrLabel] as? String ?? "Unnamed"
let tokenID = $0[kSecAttrApplicationLabel] as! Data let tokenID = $0[kSecAttrApplicationLabel] as! Data
let algorithm = Algorithm(secAttr: $0[kSecAttrKeyType] as! NSNumber) let algorithm = Algorithm(secAttr: $0[kSecAttrKeyType] as! NSNumber)
let keySize = $0[kSecAttrKeySizeInBits] as! Int let keySize = $0[kSecAttrKeySizeInBits] as! Int
@ -199,91 +150,7 @@ extension SmartCard.Store {
let publicKey = publicKeyAttributes[kSecValueData] as! Data let publicKey = publicKeyAttributes[kSecValueData] as! Data
return SmartCard.Secret(id: tokenID, name: name, algorithm: algorithm, keySize: keySize, publicKey: publicKey) return SmartCard.Secret(id: tokenID, name: name, algorithm: algorithm, keySize: keySize, publicKey: publicKey)
} }
state.withLock { secrets.append(contentsOf: wrapped)
$0.secrets.append(contentsOf: wrapped)
}
}
}
// MARK: Smart Card specific encryption/decryption/verification
extension SmartCard.Store {
/// Encrypts a payload with a specified key.
/// - Parameters:
/// - data: The payload to encrypt.
/// - secret: The secret to encrypt with.
/// - Returns: The encrypted data.
/// - Warning: Encryption functions are deliberately only exposed on a library level, and are not exposed in Secretive itself to prevent users from data loss. Any pull requests which expose this functionality in the app will not be merged.
public func encrypt(data: Data, with secret: SecretType) throws -> Data {
let context = LAContext()
context.localizedReason = String(localized: "auth_context_request_encrypt_description_\(secret.name)")
context.localizedCancelTitle = String(localized: "auth_context_request_deny_button")
let attributes = KeychainDictionary([
kSecAttrKeyType: secret.algorithm.secAttrKeyType,
kSecAttrKeySizeInBits: secret.keySize,
kSecAttrKeyClass: kSecAttrKeyClassPublic,
kSecUseAuthenticationContext: context
])
var encryptError: SecurityError?
let untyped: CFTypeRef? = SecKeyCreateWithData(secret.publicKey as CFData, attributes, &encryptError)
guard let untypedSafe = untyped else {
throw KeychainError(statusCode: errSecSuccess)
}
let key = untypedSafe as! SecKey
guard let signature = SecKeyCreateEncryptedData(key, encryptionAlgorithm(for: secret), data as CFData, &encryptError) else {
throw SigningError(error: encryptError)
}
return signature as Data
}
/// Decrypts a payload with a specified key.
/// - Parameters:
/// - data: The payload to decrypt.
/// - secret: The secret to decrypt with.
/// - Returns: The decrypted data.
/// - Warning: Encryption functions are deliberately only exposed on a library level, and are not exposed in Secretive itself to prevent users from data loss. Any pull requests which expose this functionality in the app will not be merged.
public func decrypt(data: Data, with secret: SecretType) throws -> Data {
guard let tokenID = state.withLock({ $0.tokenID }) else { fatalError() }
let context = LAContext()
context.localizedReason = String(localized: "auth_context_request_decrypt_description_\(secret.name)")
context.localizedCancelTitle = String(localized: "auth_context_request_deny_button")
let attributes = KeychainDictionary([
kSecClass: kSecClassKey,
kSecAttrKeyClass: kSecAttrKeyClassPrivate,
kSecAttrApplicationLabel: secret.id as CFData,
kSecAttrTokenID: tokenID,
kSecUseAuthenticationContext: context,
kSecReturnRef: true
])
var untyped: CFTypeRef?
let status = SecItemCopyMatching(attributes, &untyped)
if status != errSecSuccess {
throw KeychainError(statusCode: status)
}
guard let untypedSafe = untyped else {
throw KeychainError(statusCode: errSecSuccess)
}
let key = untypedSafe as! SecKey
var encryptError: SecurityError?
guard let signature = SecKeyCreateDecryptedData(key, encryptionAlgorithm(for: secret), data as CFData, &encryptError) else {
throw SigningError(error: encryptError)
}
return signature as Data
}
private func encryptionAlgorithm(for secret: SecretType) -> SecKeyAlgorithm {
switch (secret.algorithm, secret.keySize) {
case (.ellipticCurve, 256):
return .eciesEncryptionCofactorVariableIVX963SHA256AESGCM
case (.ellipticCurve, 384):
return .eciesEncryptionCofactorVariableIVX963SHA384AESGCM
case (.rsa, 1024), (.rsa, 2048):
return .rsaEncryptionOAEPSHA512AESGCM
default:
fatalError()
}
} }
} }
@ -296,3 +163,25 @@ extension TKTokenWatcher {
} }
} }
extension SmartCard {
/// A wrapper around an error code reported by a Keychain API.
public struct KeychainError: Error {
/// The status code involved.
public let statusCode: OSStatus
}
/// A signing-related error.
public struct SigningError: Error {
/// The underlying error reported by the API, if one was returned.
public let error: SecurityError?
}
}
extension SmartCard {
public typealias SecurityError = Unmanaged<CFError>
}

View File

@ -1,69 +1,57 @@
import Testing import XCTest
import Foundation
@testable import Brief @testable import Brief
class ReleaseParsingTests: XCTestCase {
@Suite struct ReleaseParsingTests { func testNonCritical() {
@Test
func nonCritical() {
let release = Release(name: "1.0.0", prerelease: false, html_url: URL(string: "https://example.com")!, body: "Initial release") let release = Release(name: "1.0.0", prerelease: false, html_url: URL(string: "https://example.com")!, body: "Initial release")
#expect(release.critical == false) XCTAssert(release.critical == false)
} }
@Test func testCritical() {
func critical() {
let release = Release(name: "1.0.0", prerelease: false, html_url: URL(string: "https://example.com")!, body: "Critical Security Update") let release = Release(name: "1.0.0", prerelease: false, html_url: URL(string: "https://example.com")!, body: "Critical Security Update")
#expect(release.critical == true) XCTAssert(release.critical == true)
} }
@Test func testOSMissing() {
func osMissing() {
let release = Release(name: "1.0.0", prerelease: false, html_url: URL(string: "https://example.com")!, body: "Critical Security Update") let release = Release(name: "1.0.0", prerelease: false, html_url: URL(string: "https://example.com")!, body: "Critical Security Update")
#expect(release.minimumOSVersion == SemVer("11.0.0")) XCTAssert(release.minimumOSVersion == SemVer("11.0.0"))
} }
@Test func testOSPresentWithContentBelow() {
func osPresentWithContentBelow() {
let release = Release(name: "1.0.0", prerelease: false, html_url: URL(string: "https://example.com")!, body: "Critical Security Update ##Minimum macOS Version\n1.2.3\nBuild info") let release = Release(name: "1.0.0", prerelease: false, html_url: URL(string: "https://example.com")!, body: "Critical Security Update ##Minimum macOS Version\n1.2.3\nBuild info")
#expect(release.minimumOSVersion == SemVer("1.2.3")) XCTAssert(release.minimumOSVersion == SemVer("1.2.3"))
} }
@Test func testOSPresentAtEnd() {
func osPresentAtEnd() {
let release = Release(name: "1.0.0", prerelease: false, html_url: URL(string: "https://example.com")!, body: "Critical Security Update Minimum macOS Version: 1.2.3") let release = Release(name: "1.0.0", prerelease: false, html_url: URL(string: "https://example.com")!, body: "Critical Security Update Minimum macOS Version: 1.2.3")
#expect(release.minimumOSVersion == SemVer("1.2.3")) XCTAssert(release.minimumOSVersion == SemVer("1.2.3"))
} }
@Test func testOSWithMacOSPrefix() {
func osWithMacOSPrefix() {
let release = Release(name: "1.0.0", prerelease: false, html_url: URL(string: "https://example.com")!, body: "Critical Security Update Minimum macOS Version: macOS 1.2.3") let release = Release(name: "1.0.0", prerelease: false, html_url: URL(string: "https://example.com")!, body: "Critical Security Update Minimum macOS Version: macOS 1.2.3")
#expect(release.minimumOSVersion == SemVer("1.2.3")) XCTAssert(release.minimumOSVersion == SemVer("1.2.3"))
} }
@Test func testOSGreaterThanMinimum() {
func osGreaterThanMinimum() {
let release = Release(name: "1.0.0", prerelease: false, html_url: URL(string: "https://example.com")!, body: "Critical Security Update Minimum macOS Version: 1.2.3") let release = Release(name: "1.0.0", prerelease: false, html_url: URL(string: "https://example.com")!, body: "Critical Security Update Minimum macOS Version: 1.2.3")
#expect(release.minimumOSVersion < SemVer("11.0.0")) XCTAssert(release.minimumOSVersion < SemVer("11.0.0"))
} }
@Test func testOSEqualToMinimum() {
func osEqualToMinimum() {
let release = Release(name: "1.0.0", prerelease: false, html_url: URL(string: "https://example.com")!, body: "Critical Security Update Minimum macOS Version: 11.2.3") let release = Release(name: "1.0.0", prerelease: false, html_url: URL(string: "https://example.com")!, body: "Critical Security Update Minimum macOS Version: 11.2.3")
#expect(release.minimumOSVersion <= SemVer("11.2.3")) XCTAssert(release.minimumOSVersion <= SemVer("11.2.3"))
} }
@Test func testOSLessThanMinimum() {
func osLessThanMinimum() {
let release = Release(name: "1.0.0", prerelease: false, html_url: URL(string: "https://example.com")!, body: "Critical Security Update Minimum macOS Version: 1.2.3") let release = Release(name: "1.0.0", prerelease: false, html_url: URL(string: "https://example.com")!, body: "Critical Security Update Minimum macOS Version: 1.2.3")
#expect(release.minimumOSVersion > SemVer("1.0.0")) XCTAssert(release.minimumOSVersion > SemVer("1.0.0"))
} }
@Test func testGreatestSelectedIfOldPatchIsPublishedLater() {
func greatestSelectedIfOldPatchIsPublishedLater() async throws {
// If 2.x.x series has been published, and a patch for 1.x.x is issued // If 2.x.x series has been published, and a patch for 1.x.x is issued
// 2.x.x should still be selected if user can run it. // 2.x.x should still be selected if user can run it.
let updater = Updater(checkOnLaunch: false, osVersion: SemVer("2.2.3"), currentVersion: SemVer("1.0.0")) let updater = UpdateChecker(checkOnLaunch: false, osVersion: SemVer("2.2.3"), currentVersion: SemVer("1.0.0"))
let two = Release(name: "2.0.0", prerelease: false, html_url: URL(string: "https://example.com")!, body: "2.0 available! Minimum macOS Version: 2.2.3") let two = Release(name: "2.0.0", prerelease: false, html_url: URL(string: "https://example.com")!, body: "2.0 available! Minimum macOS Version: 2.2.3")
let releases = [ let releases = [
Release(name: "1.0.0", prerelease: false, html_url: URL(string: "https://example.com")!, body: "Initial release Minimum macOS Version: 1.2.3"), Release(name: "1.0.0", prerelease: false, html_url: URL(string: "https://example.com")!, body: "Initial release Minimum macOS Version: 1.2.3"),
@ -72,16 +60,19 @@ import Foundation
Release(name: "1.0.2", prerelease: false, html_url: URL(string: "https://example.com")!, body: "Emergency patch! Minimum macOS Version: 1.2.3"), Release(name: "1.0.2", prerelease: false, html_url: URL(string: "https://example.com")!, body: "Emergency patch! Minimum macOS Version: 1.2.3"),
] ]
await updater.evaluate(releases: releases) let expectation = XCTestExpectation()
try await Task.sleep(nanoseconds: 1) updater.evaluate(releases: releases)
#expect(updater.update == two) DispatchQueue.main.async {
XCTAssert(updater.update == two)
expectation.fulfill()
}
wait(for: [expectation], timeout: 1)
} }
@Test func testLatestVersionIsRunnable() {
func latestVersionIsRunnable() async throws {
// If the 2.x.x series has been published but the user can't run it // If the 2.x.x series has been published but the user can't run it
// the last version the user can run should be selected. // the last version the user can run should be selected.
let updater = Updater(checkOnLaunch: false, osVersion: SemVer("1.2.3"), currentVersion: SemVer("1.0.0")) let updater = UpdateChecker(checkOnLaunch: false, osVersion: SemVer("1.2.3"), currentVersion: SemVer("1.0.0"))
let oneOhTwo = Release(name: "1.0.2", prerelease: false, html_url: URL(string: "https://example.com")!, body: "Emergency patch! Minimum macOS Version: 1.2.3") let oneOhTwo = Release(name: "1.0.2", prerelease: false, html_url: URL(string: "https://example.com")!, body: "Emergency patch! Minimum macOS Version: 1.2.3")
let releases = [ let releases = [
Release(name: "1.0.0", prerelease: false, html_url: URL(string: "https://example.com")!, body: "Initial release Minimum macOS Version: 1.2.3"), Release(name: "1.0.0", prerelease: false, html_url: URL(string: "https://example.com")!, body: "Initial release Minimum macOS Version: 1.2.3"),
@ -89,13 +80,16 @@ import Foundation
Release(name: "2.0.0", prerelease: false, html_url: URL(string: "https://example.com")!, body: "2.0 available! Minimum macOS Version: 2.2.3"), Release(name: "2.0.0", prerelease: false, html_url: URL(string: "https://example.com")!, body: "2.0 available! Minimum macOS Version: 2.2.3"),
Release(name: "1.0.2", prerelease: false, html_url: URL(string: "https://example.com")!, body: "Emergency patch! Minimum macOS Version: 1.2.3"), Release(name: "1.0.2", prerelease: false, html_url: URL(string: "https://example.com")!, body: "Emergency patch! Minimum macOS Version: 1.2.3"),
] ]
await updater.evaluate(releases: releases) let expectation = XCTestExpectation()
try await Task.sleep(nanoseconds: 1) updater.evaluate(releases: releases)
#expect(updater.update == oneOhTwo) DispatchQueue.main.async {
XCTAssert(updater.update == oneOhTwo)
expectation.fulfill()
}
wait(for: [expectation], timeout: 1)
} }
@Test func testSorting() {
func sorting() {
let two = Release(name: "2.0.0", prerelease: false, html_url: URL(string: "https://example.com")!, body: "2.0 available!") let two = Release(name: "2.0.0", prerelease: false, html_url: URL(string: "https://example.com")!, body: "2.0 available!")
let releases = [ let releases = [
Release(name: "1.0.0", prerelease: false, html_url: URL(string: "https://example.com")!, body: "Initial release"), Release(name: "1.0.0", prerelease: false, html_url: URL(string: "https://example.com")!, body: "Initial release"),
@ -104,7 +98,7 @@ import Foundation
Release(name: "1.0.2", prerelease: false, html_url: URL(string: "https://example.com")!, body: "Emergency patch!"), Release(name: "1.0.2", prerelease: false, html_url: URL(string: "https://example.com")!, body: "Emergency patch!"),
] ]
let sorted = releases.sorted().reversed().first let sorted = releases.sorted().reversed().first
#expect(sorted == two) XCTAssert(sorted == two)
} }
} }

View File

@ -1,52 +1,51 @@
import Testing import XCTest
import Foundation
@testable import Brief @testable import Brief
@Suite struct SemVerTests { class SemVerTests: XCTestCase {
@Test func equal() { func testEqual() {
let current = SemVer("1.0.2") let current = SemVer("1.0.2")
let old = SemVer("1.0.2") let old = SemVer("1.0.2")
#expect(!(current > old)) XCTAssert(!(current > old))
} }
@Test func patchGreaterButMinorLess() { func testPatchGreaterButMinorLess() {
let current = SemVer("1.1.0") let current = SemVer("1.1.0")
let old = SemVer("1.0.2") let old = SemVer("1.0.2")
#expect(current > old) XCTAssert(current > old)
} }
@Test func majorSameMinorGreater() { func testMajorSameMinorGreater() {
let current = SemVer("1.0.2") let current = SemVer("1.0.2")
let new = SemVer("1.0.3") let new = SemVer("1.0.3")
#expect(current < new) XCTAssert(current < new)
} }
@Test func majorGreaterMinorLesser() { func testMajorGreaterMinorLesser() {
let current = SemVer("1.0.2") let current = SemVer("1.0.2")
let new = SemVer("2.0.0") let new = SemVer("2.0.0")
#expect(current < new) XCTAssert(current < new)
} }
@Test func regularParsing() { func testRegularParsing() {
let current = SemVer("1.0.2") let current = SemVer("1.0.2")
#expect(current.versionNumbers == [1, 0, 2]) XCTAssert(current.versionNumbers == [1, 0, 2])
} }
@Test func noPatch() { func testNoPatch() {
let current = SemVer("1.1") let current = SemVer("1.1")
#expect(current.versionNumbers == [1, 1, 0]) XCTAssert(current.versionNumbers == [1, 1, 0])
} }
@Test func garbage() { func testGarbage() {
let current = SemVer("Test") let current = SemVer("Test")
#expect(current.versionNumbers == [0, 0, 0]) XCTAssert(current.versionNumbers == [0, 0, 0])
} }
@Test func beta() { func testBeta() {
let current = SemVer("1.0.2") let current = SemVer("1.0.2")
let new = SemVer("1.1.0_beta1") let new = SemVer("1.1.0_beta1")
#expect(current < new) XCTAssert(current < new)
} }
} }

View File

@ -1,48 +1,48 @@
import Foundation import Foundation
import Testing import XCTest
import CryptoKit import CryptoKit
@testable import SecretKit @testable import SecretKit
@testable import SecretAgentKit @testable import SecretAgentKit
@Suite struct AgentTests { class AgentTests: XCTestCase {
let stubWriter = StubFileHandleWriter() let stubWriter = StubFileHandleWriter()
// MARK: Identity Listing // MARK: Identity Listing
@Test func emptyStores() async { func testEmptyStores() {
let stubReader = StubFileHandleReader(availableData: Constants.Requests.requestIdentities) let stubReader = StubFileHandleReader(availableData: Constants.Requests.requestIdentities)
let agent = Agent(storeList: SecretStoreList()) let agent = Agent(storeList: SecretStoreList())
await agent.handle(reader: stubReader, writer: stubWriter) agent.handle(reader: stubReader, writer: stubWriter)
#expect(stubWriter.data == Constants.Responses.requestIdentitiesEmpty) XCTAssertEqual(stubWriter.data, Constants.Responses.requestIdentitiesEmpty)
} }
@Test func identitiesList() async { func testIdentitiesList() {
let stubReader = StubFileHandleReader(availableData: Constants.Requests.requestIdentities) let stubReader = StubFileHandleReader(availableData: Constants.Requests.requestIdentities)
let list = storeList(with: [Constants.Secrets.ecdsa256Secret, Constants.Secrets.ecdsa384Secret]) let list = storeList(with: [Constants.Secrets.ecdsa256Secret, Constants.Secrets.ecdsa384Secret])
let agent = Agent(storeList: list) let agent = Agent(storeList: list)
await agent.handle(reader: stubReader, writer: stubWriter) agent.handle(reader: stubReader, writer: stubWriter)
#expect(stubWriter.data == Constants.Responses.requestIdentitiesMultiple) XCTAssertEqual(stubWriter.data, Constants.Responses.requestIdentitiesMultiple)
} }
// MARK: Signatures // MARK: Signatures
@Test func noMatchingIdentities() async { func testNoMatchingIdentities() {
let stubReader = StubFileHandleReader(availableData: Constants.Requests.requestSignatureWithNoneMatching) let stubReader = StubFileHandleReader(availableData: Constants.Requests.requestSignatureWithNoneMatching)
let list = storeList(with: [Constants.Secrets.ecdsa256Secret, Constants.Secrets.ecdsa384Secret]) let list = storeList(with: [Constants.Secrets.ecdsa256Secret, Constants.Secrets.ecdsa384Secret])
let agent = Agent(storeList: list) let agent = Agent(storeList: list)
await agent.handle(reader: stubReader, writer: stubWriter) agent.handle(reader: stubReader, writer: stubWriter)
#expect(stubWriter.data == Constants.Responses.requestFailure) // XCTAssertEqual(stubWriter.data, Constants.Responses.requestFailure)
} }
@Test func signature() async throws { func testSignature() {
let stubReader = StubFileHandleReader(availableData: Constants.Requests.requestSignature) let stubReader = StubFileHandleReader(availableData: Constants.Requests.requestSignature)
let requestReader = OpenSSHReader(data: Constants.Requests.requestSignature[5...]) let requestReader = OpenSSHReader(data: Constants.Requests.requestSignature[5...])
_ = requestReader.readNextChunk() _ = requestReader.readNextChunk()
let dataToSign = requestReader.readNextChunk() let dataToSign = requestReader.readNextChunk()
let list = storeList(with: [Constants.Secrets.ecdsa256Secret, Constants.Secrets.ecdsa384Secret]) let list = storeList(with: [Constants.Secrets.ecdsa256Secret, Constants.Secrets.ecdsa384Secret])
let agent = Agent(storeList: list) let agent = Agent(storeList: list)
await agent.handle(reader: stubReader, writer: stubWriter) agent.handle(reader: stubReader, writer: stubWriter)
let outer = OpenSSHReader(data: stubWriter.data[5...]) let outer = OpenSSHReader(data: stubWriter.data[5...])
let payload = outer.readNextChunk() let payload = outer.readNextChunk()
let inner = OpenSSHReader(data: payload) let inner = OpenSSHReader(data: payload)
@ -61,33 +61,24 @@ import CryptoKit
var rs = r var rs = r
rs.append(s) rs.append(s)
let signature = try! P256.Signing.ECDSASignature(rawRepresentation: rs) let signature = try! P256.Signing.ECDSASignature(rawRepresentation: rs)
let referenceValid = try! P256.Signing.PublicKey(x963Representation: Constants.Secrets.ecdsa256Secret.publicKey).isValidSignature(signature, for: dataToSign) let valid = try! P256.Signing.PublicKey(x963Representation: Constants.Secrets.ecdsa256Secret.publicKey).isValidSignature(signature, for: dataToSign)
let store = list.stores.first! XCTAssertTrue(valid)
let derVerifies = try await store.verify(signature: signature.derRepresentation, for: dataToSign, with: AnySecret(Constants.Secrets.ecdsa256Secret))
let invalidRandomSignature = try await store.verify(signature: "invalid".data(using: .utf8)!, for: dataToSign, with: AnySecret(Constants.Secrets.ecdsa256Secret))
let invalidRandomData = try await store.verify(signature: signature.derRepresentation, for: "invalid".data(using: .utf8)!, with: AnySecret(Constants.Secrets.ecdsa256Secret))
let invalidWrongKey = try await store.verify(signature: signature.derRepresentation, for: dataToSign, with: AnySecret(Constants.Secrets.ecdsa384Secret))
#expect(referenceValid)
#expect(derVerifies)
#expect(invalidRandomSignature == false)
#expect(invalidRandomData == false)
#expect(invalidWrongKey == false)
} }
// MARK: Witness protocol // MARK: Witness protocol
@Test func witnessObjectionStopsRequest() async { func testWitnessObjectionStopsRequest() {
let stubReader = StubFileHandleReader(availableData: Constants.Requests.requestSignature) let stubReader = StubFileHandleReader(availableData: Constants.Requests.requestSignature)
let list = storeList(with: [Constants.Secrets.ecdsa256Secret]) let list = storeList(with: [Constants.Secrets.ecdsa256Secret])
let witness = StubWitness(speakNow: { _,_ in let witness = StubWitness(speakNow: { _,_ in
return true return true
}, witness: { _, _ in }) }, witness: { _, _ in })
let agent = Agent(storeList: list, witness: witness) let agent = Agent(storeList: list, witness: witness)
await agent.handle(reader: stubReader, writer: stubWriter) agent.handle(reader: stubReader, writer: stubWriter)
#expect(stubWriter.data == Constants.Responses.requestFailure) XCTAssertEqual(stubWriter.data, Constants.Responses.requestFailure)
} }
@Test func witnessSignature() async { func testWitnessSignature() {
let stubReader = StubFileHandleReader(availableData: Constants.Requests.requestSignature) let stubReader = StubFileHandleReader(availableData: Constants.Requests.requestSignature)
let list = storeList(with: [Constants.Secrets.ecdsa256Secret]) let list = storeList(with: [Constants.Secrets.ecdsa256Secret])
var witnessed = false var witnessed = false
@ -97,11 +88,11 @@ import CryptoKit
witnessed = true witnessed = true
}) })
let agent = Agent(storeList: list, witness: witness) let agent = Agent(storeList: list, witness: witness)
await agent.handle(reader: stubReader, writer: stubWriter) agent.handle(reader: stubReader, writer: stubWriter)
#expect(witnessed) XCTAssertTrue(witnessed)
} }
@Test func requestTracing() async { func testRequestTracing() {
let stubReader = StubFileHandleReader(availableData: Constants.Requests.requestSignature) let stubReader = StubFileHandleReader(availableData: Constants.Requests.requestSignature)
let list = storeList(with: [Constants.Secrets.ecdsa256Secret]) let list = storeList(with: [Constants.Secrets.ecdsa256Secret])
var speakNowTrace: SigningRequestProvenance! = nil var speakNowTrace: SigningRequestProvenance! = nil
@ -113,32 +104,32 @@ import CryptoKit
witnessTrace = trace witnessTrace = trace
}) })
let agent = Agent(storeList: list, witness: witness) let agent = Agent(storeList: list, witness: witness)
await agent.handle(reader: stubReader, writer: stubWriter) agent.handle(reader: stubReader, writer: stubWriter)
#expect(witnessTrace == speakNowTrace) XCTAssertEqual(witnessTrace, speakNowTrace)
#expect(witnessTrace.origin.displayName == "Finder") XCTAssertEqual(witnessTrace.origin.displayName, "Finder")
#expect(witnessTrace.origin.validSignature == true) XCTAssertEqual(witnessTrace.origin.validSignature, true)
#expect(witnessTrace.origin.parentPID == 1) XCTAssertEqual(witnessTrace.origin.parentPID, 1)
} }
// MARK: Exception Handling // MARK: Exception Handling
@Test func signatureException() async { func testSignatureException() {
let stubReader = StubFileHandleReader(availableData: Constants.Requests.requestSignature) let stubReader = StubFileHandleReader(availableData: Constants.Requests.requestSignature)
let list = storeList(with: [Constants.Secrets.ecdsa256Secret, Constants.Secrets.ecdsa384Secret]) let list = storeList(with: [Constants.Secrets.ecdsa256Secret, Constants.Secrets.ecdsa384Secret])
let store = list.stores.first?.base as! Stub.Store let store = list.stores.first?.base as! Stub.Store
store.shouldThrow = true store.shouldThrow = true
let agent = Agent(storeList: list) let agent = Agent(storeList: list)
await agent.handle(reader: stubReader, writer: stubWriter) agent.handle(reader: stubReader, writer: stubWriter)
#expect(stubWriter.data == Constants.Responses.requestFailure) XCTAssertEqual(stubWriter.data, Constants.Responses.requestFailure)
} }
// MARK: Unsupported // MARK: Unsupported
@Test func unhandledAdd() async { func testUnhandledAdd() {
let stubReader = StubFileHandleReader(availableData: Constants.Requests.addIdentity) let stubReader = StubFileHandleReader(availableData: Constants.Requests.addIdentity)
let agent = Agent(storeList: SecretStoreList()) let agent = Agent(storeList: SecretStoreList())
await agent.handle(reader: stubReader, writer: stubWriter) agent.handle(reader: stubReader, writer: stubWriter)
#expect(stubWriter.data == Constants.Responses.requestFailure) XCTAssertEqual(stubWriter.data, Constants.Responses.requestFailure)
} }
} }

View File

@ -1,7 +1,7 @@
import Foundation import Foundation
import SecretAgentKit import SecretAgentKit
class StubFileHandleWriter: FileHandleWriter, @unchecked Sendable { class StubFileHandleWriter: FileHandleWriter {
var data = Data() var data = Data()

View File

@ -6,7 +6,7 @@ struct Stub {}
extension Stub { extension Stub {
public final class Store: SecretStore, @unchecked Sendable { public class Store: SecretStore {
public let isAvailable = true public let isAvailable = true
public let id = UUID() public let id = UUID()
@ -27,7 +27,7 @@ extension Stub {
flags, flags,
nil) as Any nil) as Any
let attributes = KeychainDictionary([ let attributes = [
kSecAttrLabel: name, kSecAttrLabel: name,
kSecAttrKeyType: kSecAttrKeyTypeECSECPrimeRandom, kSecAttrKeyType: kSecAttrKeyTypeECSECPrimeRandom,
kSecAttrKeySizeInBits: size, kSecAttrKeySizeInBits: size,
@ -35,10 +35,11 @@ extension Stub {
kSecAttrIsPermanent: true, kSecAttrIsPermanent: true,
kSecAttrAccessControl: access kSecAttrAccessControl: access
] ]
]) ] as CFDictionary
let privateKey = SecKeyCreateRandomKey(attributes, nil)! var privateKey: SecKey! = nil
let publicKey = SecKeyCopyPublicKey(privateKey)! var publicKey: SecKey! = nil
SecKeyGeneratePair(attributes, &publicKey, &privateKey)
let publicAttributes = SecKeyCopyAttributes(publicKey) as! [CFString: Any] let publicAttributes = SecKeyCopyAttributes(publicKey) as! [CFString: Any]
let privateAttributes = SecKeyCopyAttributes(privateKey) as! [CFString: Any] let privateAttributes = SecKeyCopyAttributes(privateKey) as! [CFString: Any]
let publicData = (publicAttributes[kSecValueData] as! Data) let publicData = (publicAttributes[kSecValueData] as! Data)
@ -48,52 +49,31 @@ extension Stub {
print("Public Key OpenSSH: \(OpenSSHKeyWriter().openSSHString(secret: secret))") print("Public Key OpenSSH: \(OpenSSHKeyWriter().openSSHString(secret: secret))")
} }
public func sign(data: Data, with secret: Secret, for provenance: SigningRequestProvenance) throws -> Data { public func sign(data: Data, with secret: Secret, for provenance: SigningRequestProvenance) throws -> SignedData {
guard !shouldThrow else { guard !shouldThrow else {
throw NSError(domain: "test", code: 0, userInfo: nil) throw NSError(domain: "test", code: 0, userInfo: nil)
} }
let privateKey = SecKeyCreateWithData(secret.privateKey as CFData, KeychainDictionary([ let privateKey = SecKeyCreateWithData(secret.privateKey as CFData, [
kSecAttrKeyType: kSecAttrKeyTypeECSECPrimeRandom, kSecAttrKeyType: kSecAttrKeyTypeECSECPrimeRandom,
kSecAttrKeySizeInBits: secret.keySize, kSecAttrKeySizeInBits: secret.keySize,
kSecAttrKeyClass: kSecAttrKeyClassPrivate kSecAttrKeyClass: kSecAttrKeyClassPrivate
]) ] as CFDictionary
, nil)! , nil)!
return SecKeyCreateSignature(privateKey, signatureAlgorithm(for: secret), data as CFData, nil)! as Data let signatureAlgorithm: SecKeyAlgorithm
} switch secret.keySize {
case 256:
public func verify(signature: Data, for data: Data, with secret: Stub.Secret) throws -> Bool { signatureAlgorithm = .ecdsaSignatureMessageX962SHA256
let attributes = KeychainDictionary([ case 384:
kSecAttrKeyType: secret.algorithm.secAttrKeyType, signatureAlgorithm = .ecdsaSignatureMessageX962SHA384
kSecAttrKeySizeInBits: secret.keySize, default:
kSecAttrKeyClass: kSecAttrKeyClassPublic fatalError()
])
var verifyError: Unmanaged<CFError>?
let untyped: CFTypeRef? = SecKeyCreateWithData(secret.publicKey as CFData, attributes, &verifyError)
guard let untypedSafe = untyped else {
throw NSError(domain: "test", code: 0, userInfo: nil)
} }
let key = untypedSafe as! SecKey return SignedData(data: SecKeyCreateSignature(privateKey, signatureAlgorithm, data as CFData, nil)! as Data, requiredAuthentication: false)
let verified = SecKeyVerifySignature(key, signatureAlgorithm(for: secret), data as CFData, signature as CFData, &verifyError)
if let verifyError {
if verifyError.takeUnretainedValue() ~= .verifyError {
return false
} else {
throw NSError(domain: "test", code: 0, userInfo: nil)
}
}
return verified
}
public func existingPersistedAuthenticationContext(secret: Stub.Secret) -> PersistedAuthenticationContext? {
nil
} }
public func persistAuthentication(secret: Stub.Secret, forDuration duration: TimeInterval) throws { public func persistAuthentication(secret: Stub.Secret, forDuration duration: TimeInterval) throws {
} }
public func reloadSecrets() {
}
} }
} }
@ -108,7 +88,6 @@ extension Stub {
let keySize: Int let keySize: Int
let publicKey: Data let publicKey: Data
let requiresAuthentication = false
let privateKey: Data let privateKey: Data
init(keySize: Int, publicKey: Data, privateKey: Data) { init(keySize: Int, publicKey: Data, privateKey: Data) {

View File

@ -17,7 +17,7 @@ func speakNowOrForeverHoldYourPeace(forAccessTo secret: AnySecret, from store: A
} }
} }
func witness(accessTo secret: AnySecret, from store: AnySecretStore, by provenance: SigningRequestProvenance) throws { func witness(accessTo secret: AnySecret, from store: AnySecretStore, by provenance: SigningRequestProvenance, requiredAuthentication: Bool) throws {
witness(secret, provenance) witness(secret, provenance)
} }

View File

@ -1,19 +1,19 @@
import Foundation import Foundation
import Testing import XCTest
@testable import SecretKit @testable import SecretKit
@testable import SecureEnclaveSecretKit @testable import SecureEnclaveSecretKit
@testable import SmartCardSecretKit @testable import SmartCardSecretKit
@Suite struct AnySecretTests { class AnySecretTests: XCTestCase {
@Test func eraser() { func testEraser() {
let secret = SmartCard.Secret(id: UUID().uuidString.data(using: .utf8)!, name: "Name", algorithm: .ellipticCurve, keySize: 256, publicKey: UUID().uuidString.data(using: .utf8)!) let secret = SmartCard.Secret(id: UUID().uuidString.data(using: .utf8)!, name: "Name", algorithm: .ellipticCurve, keySize: 256, publicKey: UUID().uuidString.data(using: .utf8)!)
let erased = AnySecret(secret) let erased = AnySecret(secret)
#expect(erased.id == secret.id as AnyHashable) XCTAssert(erased.id == secret.id as AnyHashable)
#expect(erased.name == secret.name) XCTAssert(erased.name == secret.name)
#expect(erased.algorithm == secret.algorithm) XCTAssert(erased.algorithm == secret.algorithm)
#expect(erased.keySize == secret.keySize) XCTAssert(erased.keySize == secret.keySize)
#expect(erased.publicKey == secret.publicKey) XCTAssert(erased.publicKey == secret.publicKey)
} }
} }

View File

@ -1,19 +1,19 @@
import Foundation import Foundation
import Testing import XCTest
@testable import SecretKit @testable import SecretKit
@testable import SecureEnclaveSecretKit @testable import SecureEnclaveSecretKit
@testable import SmartCardSecretKit @testable import SmartCardSecretKit
@Suite struct OpenSSHReaderTests { class OpenSSHReaderTests: XCTestCase {
@Test func signatureRequest() { func testSignatureRequest() {
let reader = OpenSSHReader(data: Constants.signatureRequest) let reader = OpenSSHReader(data: Constants.signatureRequest)
let hash = reader.readNextChunk() let hash = reader.readNextChunk()
#expect(hash == Data(base64Encoded: "AAAAE2VjZHNhLXNoYTItbmlzdHAzODQAAAAIbmlzdHAzODQAAABhBEqCbkJbOHy5S1wVCaJoKPmpS0egM4frMqllgnlRRQ/Uvnn6EVS8oV03cPA2Bz0EdESyRKA/sbmn0aBtgjIwGELxu45UXEW1TEz6TxyS0u3vuIqR3Wo1CrQWRDnkrG/pBQ==")) XCTAssert(hash == Data(base64Encoded: "AAAAE2VjZHNhLXNoYTItbmlzdHAzODQAAAAIbmlzdHAzODQAAABhBEqCbkJbOHy5S1wVCaJoKPmpS0egM4frMqllgnlRRQ/Uvnn6EVS8oV03cPA2Bz0EdESyRKA/sbmn0aBtgjIwGELxu45UXEW1TEz6TxyS0u3vuIqR3Wo1CrQWRDnkrG/pBQ=="))
let dataToSign = reader.readNextChunk() let dataToSign = reader.readNextChunk()
#expect(dataToSign == Data(base64Encoded: "AAAAICi5xf1ixOestUlxdjvt/BDcM+rzhwy7Vo8cW5YcxA8+MgAAAANnaXQAAAAOc3NoLWNvbm5lY3Rpb24AAAAJcHVibGlja2V5AQAAABNlY2RzYS1zaGEyLW5pc3RwMzg0AAAAiAAAABNlY2RzYS1zaGEyLW5pc3RwMzg0AAAACG5pc3RwMzg0AAAAYQRKgm5CWzh8uUtcFQmiaCj5qUtHoDOH6zKpZYJ5UUUP1L55+hFUvKFdN3DwNgc9BHREskSgP7G5p9GgbYIyMBhC8buOVFxFtUxM+k8cktLt77iKkd1qNQq0FkQ55Kxv6QU=")) XCTAssert(dataToSign == Data(base64Encoded: "AAAAICi5xf1ixOestUlxdjvt/BDcM+rzhwy7Vo8cW5YcxA8+MgAAAANnaXQAAAAOc3NoLWNvbm5lY3Rpb24AAAAJcHVibGlja2V5AQAAABNlY2RzYS1zaGEyLW5pc3RwMzg0AAAAiAAAABNlY2RzYS1zaGEyLW5pc3RwMzg0AAAACG5pc3RwMzg0AAAAYQRKgm5CWzh8uUtcFQmiaCj5qUtHoDOH6zKpZYJ5UUUP1L55+hFUvKFdN3DwNgc9BHREskSgP7G5p9GgbYIyMBhC8buOVFxFtUxM+k8cktLt77iKkd1qNQq0FkQ55Kxv6QU="))
let empty = reader.readNextChunk() let empty = reader.readNextChunk()
#expect(empty.isEmpty) XCTAssert(empty.isEmpty)
} }
} }

View File

@ -1,45 +1,45 @@
import Foundation import Foundation
import Testing import XCTest
@testable import SecretKit @testable import SecretKit
@testable import SecureEnclaveSecretKit @testable import SecureEnclaveSecretKit
@testable import SmartCardSecretKit @testable import SmartCardSecretKit
@Suite struct OpenSSHWriterTests { class OpenSSHWriterTests: XCTestCase {
let writer = OpenSSHKeyWriter() let writer = OpenSSHKeyWriter()
@Test func ecdsa256MD5Fingerprint() { func testECDSA256MD5Fingerprint() {
#expect(writer.openSSHMD5Fingerprint(secret: Constants.ecdsa256Secret) == "dc:60:4d:ff:c2:d9:18:8b:2f:24:40:b5:7f:43:47:e5") XCTAssertEqual(writer.openSSHMD5Fingerprint(secret: Constants.ecdsa256Secret), "dc:60:4d:ff:c2:d9:18:8b:2f:24:40:b5:7f:43:47:e5")
} }
@Test func ecdsa256SHA256Fingerprint() { func testECDSA256SHA256Fingerprint() {
#expect(writer.openSSHSHA256Fingerprint(secret: Constants.ecdsa256Secret) == "SHA256:/VQFeGyM8qKA8rB6WGMuZZxZLJln2UgXLk3F0uTF650") XCTAssertEqual(writer.openSSHSHA256Fingerprint(secret: Constants.ecdsa256Secret), "SHA256:/VQFeGyM8qKA8rB6WGMuZZxZLJln2UgXLk3F0uTF650")
} }
@Test func ecdsa256PublicKey() { func testECDSA256PublicKey() {
#expect(writer.openSSHString(secret: Constants.ecdsa256Secret) == XCTAssertEqual(writer.openSSHString(secret: Constants.ecdsa256Secret),
"ecdsa-sha2-nistp256 AAAAE2VjZHNhLXNoYTItbmlzdHAyNTYAAAAIbmlzdHAyNTYAAABBBOVEjgAA5PHqRgwykjN5qM21uWCHFSY/Sqo5gkHAkn+e1MMQKHOLga7ucB9b3mif33MBid59GRK9GEPVlMiSQwo=") "ecdsa-sha2-nistp256 AAAAE2VjZHNhLXNoYTItbmlzdHAyNTYAAAAIbmlzdHAyNTYAAABBBOVEjgAA5PHqRgwykjN5qM21uWCHFSY/Sqo5gkHAkn+e1MMQKHOLga7ucB9b3mif33MBid59GRK9GEPVlMiSQwo=")
} }
@Test func ecdsa256Hash() { func testECDSA256Hash() {
#expect(writer.data(secret: Constants.ecdsa256Secret) == Data(base64Encoded: "AAAAE2VjZHNhLXNoYTItbmlzdHAyNTYAAAAIbmlzdHAyNTYAAABBBOVEjgAA5PHqRgwykjN5qM21uWCHFSY/Sqo5gkHAkn+e1MMQKHOLga7ucB9b3mif33MBid59GRK9GEPVlMiSQwo=")) XCTAssertEqual(writer.data(secret: Constants.ecdsa256Secret), Data(base64Encoded: "AAAAE2VjZHNhLXNoYTItbmlzdHAyNTYAAAAIbmlzdHAyNTYAAABBBOVEjgAA5PHqRgwykjN5qM21uWCHFSY/Sqo5gkHAkn+e1MMQKHOLga7ucB9b3mif33MBid59GRK9GEPVlMiSQwo="))
} }
@Test func ecdsa384MD5Fingerprint() { func testECDSA384MD5Fingerprint() {
#expect(writer.openSSHMD5Fingerprint(secret: Constants.ecdsa384Secret) == "66:e0:66:d7:41:ed:19:8e:e2:20:df:ce:ac:7e:2b:6e") XCTAssertEqual(writer.openSSHMD5Fingerprint(secret: Constants.ecdsa384Secret), "66:e0:66:d7:41:ed:19:8e:e2:20:df:ce:ac:7e:2b:6e")
} }
@Test func ecdsa384SHA256Fingerprint() { func testECDSA384SHA256Fingerprint() {
#expect(writer.openSSHSHA256Fingerprint(secret: Constants.ecdsa384Secret) == "SHA256:GJUEymQNL9ymaMRRJCMGY4rWIJHu/Lm8Yhao/PAiz1I") XCTAssertEqual(writer.openSSHSHA256Fingerprint(secret: Constants.ecdsa384Secret), "SHA256:GJUEymQNL9ymaMRRJCMGY4rWIJHu/Lm8Yhao/PAiz1I")
} }
@Test func ecdsa384PublicKey() { func testECDSA384PublicKey() {
#expect(writer.openSSHString(secret: Constants.ecdsa384Secret) == XCTAssertEqual(writer.openSSHString(secret: Constants.ecdsa384Secret),
"ecdsa-sha2-nistp384 AAAAE2VjZHNhLXNoYTItbmlzdHAzODQAAAAIbmlzdHAzODQAAABhBG2MNc/C5OTHFE2tBvbZCVcpOGa8vBMquiTLkH4lwkeqOPxhi+PyYUfQZMTRJNPiTyWPoMBqNiCIFRVv60yPN/AHufHaOgbdTP42EgMlMMImkAjYUEv9DESHTVIs2PW1yQ==") "ecdsa-sha2-nistp384 AAAAE2VjZHNhLXNoYTItbmlzdHAzODQAAAAIbmlzdHAzODQAAABhBG2MNc/C5OTHFE2tBvbZCVcpOGa8vBMquiTLkH4lwkeqOPxhi+PyYUfQZMTRJNPiTyWPoMBqNiCIFRVv60yPN/AHufHaOgbdTP42EgMlMMImkAjYUEv9DESHTVIs2PW1yQ==")
} }
@Test func ecdsa384Hash() { func testECDSA384Hash() {
#expect(writer.data(secret: Constants.ecdsa384Secret) == Data(base64Encoded: "AAAAE2VjZHNhLXNoYTItbmlzdHAzODQAAAAIbmlzdHAzODQAAABhBG2MNc/C5OTHFE2tBvbZCVcpOGa8vBMquiTLkH4lwkeqOPxhi+PyYUfQZMTRJNPiTyWPoMBqNiCIFRVv60yPN/AHufHaOgbdTP42EgMlMMImkAjYUEv9DESHTVIs2PW1yQ==")) XCTAssertEqual(writer.data(secret: Constants.ecdsa384Secret), Data(base64Encoded: "AAAAE2VjZHNhLXNoYTItbmlzdHAzODQAAAAIbmlzdHAzODQAAABhBG2MNc/C5OTHFE2tBvbZCVcpOGa8vBMquiTLkH4lwkeqOPxhi+PyYUfQZMTRJNPiTyWPoMBqNiCIFRVv60yPN/AHufHaOgbdTP42EgMlMMImkAjYUEv9DESHTVIs2PW1yQ=="))
} }
} }

View File

@ -6,9 +6,8 @@ import SecureEnclaveSecretKit
import SmartCardSecretKit import SmartCardSecretKit
import SecretAgentKit import SecretAgentKit
import Brief import Brief
import Observation
@main @NSApplicationMain
class AppDelegate: NSObject, NSApplicationDelegate { class AppDelegate: NSObject, NSApplicationDelegate {
private let storeList: SecretStoreList = { private let storeList: SecretStoreList = {
@ -17,7 +16,7 @@ class AppDelegate: NSObject, NSApplicationDelegate {
list.add(store: SmartCard.Store()) list.add(store: SmartCard.Store())
return list return list
}() }()
private let updater = Updater(checkOnLaunch: false) private let updater = UpdateChecker(checkOnLaunch: false)
private let notifier = Notifier() private let notifier = Notifier()
private let publicKeyFileStoreController = PublicKeyFileStoreController(homeDirectory: NSHomeDirectory()) private let publicKeyFileStoreController = PublicKeyFileStoreController(homeDirectory: NSHomeDirectory())
private lazy var agent: Agent = { private lazy var agent: Agent = {
@ -28,30 +27,20 @@ class AppDelegate: NSObject, NSApplicationDelegate {
return SocketController(path: path) return SocketController(path: path)
}() }()
private var updateSink: AnyCancellable? private var updateSink: AnyCancellable?
private let logger = Logger(subsystem: "com.maxgoedjen.secretive.secretagent", category: "AppDelegate")
func applicationDidFinishLaunching(_ aNotification: Notification) { func applicationDidFinishLaunching(_ aNotification: Notification) {
logger.debug("SecretAgent finished launching") Logger().debug("SecretAgent finished launching")
Task { @MainActor in DispatchQueue.main.async {
socketController.handler = { [agent] reader, writer in self.socketController.handler = self.agent.handle(reader:writer:)
await agent.handle(reader: reader, writer: writer)
}
} }
Task { DistributedNotificationCenter.default().addObserver(forName: .secretStoreUpdated, object: nil, queue: .main) { [self] _ in
for await _ in NotificationCenter.default.notifications(named: .secretStoreReloaded) { try? publicKeyFileStoreController.generatePublicKeys(for: storeList.stores.flatMap({ $0.secrets }), clear: true)
try? publicKeyFileStoreController.generatePublicKeys(for: storeList.allSecrets, clear: true)
}
} }
try? publicKeyFileStoreController.generatePublicKeys(for: storeList.allSecrets, clear: true) try? publicKeyFileStoreController.generatePublicKeys(for: storeList.stores.flatMap({ $0.secrets }), clear: true)
notifier.prompt() notifier.prompt()
_ = withObservationTracking { updateSink = updater.$update.sink { update in
updater.update guard let update = update else { return }
} onChange: { [updater, notifier] in self.notifier.notify(update: update, ignore: self.updater.ignore(release:))
notifier.notify(update: updater.update!) { release in
Task {
await updater.ignore(release: release)
}
}
} }
} }

View File

@ -4,26 +4,24 @@ import AppKit
import SecretKit import SecretKit
import SecretAgentKit import SecretAgentKit
import Brief import Brief
import Synchronization
final class Notifier: Sendable { class Notifier {
private let notificationDelegate = NotificationDelegate() private let notificationDelegate = NotificationDelegate()
init() { init() {
let updateAction = UNNotificationAction(identifier: Constants.updateActionIdentitifier, title: String(localized: "update_notification_update_button"), options: []) let updateAction = UNNotificationAction(identifier: Constants.updateActionIdentitifier, title: "Update", options: [])
let ignoreAction = UNNotificationAction(identifier: Constants.ignoreActionIdentitifier, title: String(localized: "update_notification_ignore_button"), options: []) let ignoreAction = UNNotificationAction(identifier: Constants.ignoreActionIdentitifier, title: "Ignore", options: [])
let updateCategory = UNNotificationCategory(identifier: Constants.updateCategoryIdentitifier, actions: [updateAction, ignoreAction], intentIdentifiers: [], options: []) let updateCategory = UNNotificationCategory(identifier: Constants.updateCategoryIdentitifier, actions: [updateAction, ignoreAction], intentIdentifiers: [], options: [])
let criticalUpdateCategory = UNNotificationCategory(identifier: Constants.criticalUpdateCategoryIdentitifier, actions: [updateAction], intentIdentifiers: [], options: []) let criticalUpdateCategory = UNNotificationCategory(identifier: Constants.criticalUpdateCategoryIdentitifier, actions: [updateAction], intentIdentifiers: [], options: [])
let rawDurations = [ let rawDurations = [
Measurement(value: 1, unit: UnitDuration.minutes), Measurement(value: 1, unit: UnitDuration.minutes),
Measurement(value: 5, unit: UnitDuration.minutes), Measurement(value: 5, unit: UnitDuration.minutes),
Measurement(value: 1, unit: UnitDuration.hours), Measurement(value: 1, unit: UnitDuration.hours)
Measurement(value: 24, unit: UnitDuration.hours)
] ]
let doNotPersistAction = UNNotificationAction(identifier: Constants.doNotPersistActionIdentitifier, title: String(localized: "persist_authentication_decline_button"), options: []) let doNotPersistAction = UNNotificationAction(identifier: Constants.doNotPersistActionIdentitifier, title: "Do Not Unlock", options: [])
var allPersistenceActions = [doNotPersistAction] var allPersistenceActions = [doNotPersistAction]
let formatter = DateComponentsFormatter() let formatter = DateComponentsFormatter()
@ -35,24 +33,20 @@ final class Notifier: Sendable {
guard let string = formatter.string(from: seconds)?.capitalized else { continue } guard let string = formatter.string(from: seconds)?.capitalized else { continue }
let identifier = Constants.persistAuthenticationCategoryIdentitifier.appending("\(seconds)") let identifier = Constants.persistAuthenticationCategoryIdentitifier.appending("\(seconds)")
let action = UNNotificationAction(identifier: identifier, title: string, options: []) let action = UNNotificationAction(identifier: identifier, title: string, options: [])
notificationDelegate.state.withLock { state in notificationDelegate.persistOptions[identifier] = seconds
state.persistOptions[identifier] = seconds
}
allPersistenceActions.append(action) allPersistenceActions.append(action)
} }
let persistAuthenticationCategory = UNNotificationCategory(identifier: Constants.persistAuthenticationCategoryIdentitifier, actions: allPersistenceActions, intentIdentifiers: [], options: []) let persistAuthenticationCategory = UNNotificationCategory(identifier: Constants.persistAuthenticationCategoryIdentitifier, actions: allPersistenceActions, intentIdentifiers: [], options: [])
if persistAuthenticationCategory.responds(to: Selector(("actionsMenuTitle"))) { if persistAuthenticationCategory.responds(to: Selector(("actionsMenuTitle"))) {
persistAuthenticationCategory.setValue(String(localized: "persist_authentication_accept_button"), forKey: "_actionsMenuTitle") persistAuthenticationCategory.setValue("Leave Unlocked", forKey: "_actionsMenuTitle")
} }
UNUserNotificationCenter.current().setNotificationCategories([updateCategory, criticalUpdateCategory, persistAuthenticationCategory]) UNUserNotificationCenter.current().setNotificationCategories([updateCategory, criticalUpdateCategory, persistAuthenticationCategory])
UNUserNotificationCenter.current().delegate = notificationDelegate UNUserNotificationCenter.current().delegate = notificationDelegate
notificationDelegate.state.withLock { state in notificationDelegate.persistAuthentication = { secret, store, duration in
state.persistAuthentication = { secret, store, duration in guard let duration = duration else { return }
guard let duration = duration else { return } try? store.persistAuthentication(secret: secret, forDuration: duration)
try? await store.persistAuthentication(secret: secret, forDuration: duration)
}
} }
} }
@ -62,42 +56,42 @@ final class Notifier: Sendable {
notificationCenter.requestAuthorization(options: .alert) { _, _ in } notificationCenter.requestAuthorization(options: .alert) { _, _ in }
} }
func notify(accessTo secret: AnySecret, from store: AnySecretStore, by provenance: SigningRequestProvenance) async { func notify(accessTo secret: AnySecret, from store: AnySecretStore, by provenance: SigningRequestProvenance, requiredAuthentication: Bool) {
notificationDelegate.state.withLock { state in notificationDelegate.pendingPersistableSecrets[secret.id.description] = secret
state.pendingPersistableSecrets[secret.id.description] = secret notificationDelegate.pendingPersistableStores[store.id.description] = store
state.pendingPersistableStores[store.id.description] = store
}
let notificationCenter = UNUserNotificationCenter.current() let notificationCenter = UNUserNotificationCenter.current()
let notificationContent = UNMutableNotificationContent() let notificationContent = UNMutableNotificationContent()
notificationContent.title = String(localized: "signed_notification_title_\(provenance.origin.displayName)") notificationContent.title = "Signed Request from \(provenance.origin.displayName)"
notificationContent.subtitle = String(localized: "signed_notification_description_\(secret.name)") notificationContent.subtitle = "Using secret \"\(secret.name)\""
notificationContent.userInfo[Constants.persistSecretIDKey] = secret.id.description notificationContent.userInfo[Constants.persistSecretIDKey] = secret.id.description
notificationContent.userInfo[Constants.persistStoreIDKey] = store.id.description notificationContent.userInfo[Constants.persistStoreIDKey] = store.id.description
notificationContent.interruptionLevel = .timeSensitive if #available(macOS 12.0, *) {
if await store.existingPersistedAuthenticationContext(secret: secret) == nil && secret.requiresAuthentication { notificationContent.interruptionLevel = .timeSensitive
}
if requiredAuthentication {
notificationContent.categoryIdentifier = Constants.persistAuthenticationCategoryIdentitifier notificationContent.categoryIdentifier = Constants.persistAuthenticationCategoryIdentitifier
} }
if let iconURL = provenance.origin.iconURL, let attachment = try? UNNotificationAttachment(identifier: "icon", url: iconURL, options: nil) { if let iconURL = provenance.origin.iconURL, let attachment = try? UNNotificationAttachment(identifier: "icon", url: iconURL, options: nil) {
notificationContent.attachments = [attachment] notificationContent.attachments = [attachment]
} }
let request = UNNotificationRequest(identifier: UUID().uuidString, content: notificationContent, trigger: nil) let request = UNNotificationRequest(identifier: UUID().uuidString, content: notificationContent, trigger: nil)
try? await notificationCenter.add(request) notificationCenter.add(request, withCompletionHandler: nil)
} }
func notify(update: Release, ignore: ((Release) -> Void)?) { func notify(update: Release, ignore: ((Release) -> Void)?) {
notificationDelegate.state.withLock { [update] state in notificationDelegate.release = update
state.release = update notificationDelegate.ignore = ignore
// state.ignore = ignore
}
let notificationCenter = UNUserNotificationCenter.current() let notificationCenter = UNUserNotificationCenter.current()
let notificationContent = UNMutableNotificationContent() let notificationContent = UNMutableNotificationContent()
if update.critical { if update.critical {
notificationContent.interruptionLevel = .critical if #available(macOS 12.0, *) {
notificationContent.title = String(localized: "update_notification_update_critical_title_\(update.name)") notificationContent.interruptionLevel = .critical
}
notificationContent.title = "Critical Security Update - \(update.name)"
} else { } else {
notificationContent.title = String(localized: "update_notification_update_normal_title_\(update.name)") notificationContent.title = "Update Available - \(update.name)"
} }
notificationContent.subtitle = String(localized: "update_notification_update_description") notificationContent.subtitle = "Click to Update"
notificationContent.body = update.body notificationContent.body = update.body
notificationContent.categoryIdentifier = update.critical ? Constants.criticalUpdateCategoryIdentitifier : Constants.updateCategoryIdentitifier notificationContent.categoryIdentifier = update.critical ? Constants.criticalUpdateCategoryIdentitifier : Constants.updateCategoryIdentitifier
let request = UNNotificationRequest(identifier: UUID().uuidString, content: notificationContent, trigger: nil) let request = UNNotificationRequest(identifier: UUID().uuidString, content: notificationContent, trigger: nil)
@ -108,11 +102,11 @@ final class Notifier: Sendable {
extension Notifier: SigningWitness { extension Notifier: SigningWitness {
func speakNowOrForeverHoldYourPeace(forAccessTo secret: AnySecret, from store: AnySecretStore, by provenance: SigningRequestProvenance) async throws { func speakNowOrForeverHoldYourPeace(forAccessTo secret: AnySecret, from store: AnySecretStore, by provenance: SigningRequestProvenance) throws {
} }
func witness(accessTo secret: AnySecret, from store: AnySecretStore, by provenance: SigningRequestProvenance) async throws { func witness(accessTo secret: AnySecret, from store: AnySecretStore, by provenance: SigningRequestProvenance, requiredAuthentication: Bool) throws {
await notify(accessTo: secret, from: store, by: provenance) notify(accessTo: secret, from: store, by: provenance, requiredAuthentication: requiredAuthentication)
} }
} }
@ -138,66 +132,55 @@ extension Notifier {
} }
final class NotificationDelegate: NSObject, UNUserNotificationCenterDelegate, Sendable { class NotificationDelegate: NSObject, UNUserNotificationCenterDelegate {
struct State { fileprivate var release: Release?
typealias PersistAuthentication = ((AnySecret, AnySecretStore, TimeInterval?) async -> Void) fileprivate var ignore: ((Release) -> Void)?
typealias Ignore = ((Release) -> Void) fileprivate var persistAuthentication: ((AnySecret, AnySecretStore, TimeInterval?) -> Void)?
fileprivate var release: Release? fileprivate var persistOptions: [String: TimeInterval] = [:]
fileprivate var ignore: Ignore? fileprivate var pendingPersistableStores: [String: AnySecretStore] = [:]
fileprivate var persistAuthentication: PersistAuthentication? fileprivate var pendingPersistableSecrets: [String: AnySecret] = [:]
fileprivate var persistOptions: [String: TimeInterval] = [:]
fileprivate var pendingPersistableStores: [String: AnySecretStore] = [:]
fileprivate var pendingPersistableSecrets: [String: AnySecret] = [:]
}
fileprivate let state: Mutex<State> = .init(.init())
func userNotificationCenter(_ center: UNUserNotificationCenter, openSettingsFor notification: UNNotification?) { func userNotificationCenter(_ center: UNUserNotificationCenter, openSettingsFor notification: UNNotification?) {
} }
func userNotificationCenter(_ center: UNUserNotificationCenter, didReceive response: UNNotificationResponse) async { func userNotificationCenter(_ center: UNUserNotificationCenter, didReceive response: UNNotificationResponse, withCompletionHandler completionHandler: @escaping () -> Void) {
let category = response.notification.request.content.categoryIdentifier let category = response.notification.request.content.categoryIdentifier
switch category { switch category {
case Notifier.Constants.updateCategoryIdentitifier: case Notifier.Constants.updateCategoryIdentitifier:
handleUpdateResponse(response: response) handleUpdateResponse(response: response)
case Notifier.Constants.persistAuthenticationCategoryIdentitifier: case Notifier.Constants.persistAuthenticationCategoryIdentitifier:
await handlePersistAuthenticationResponse(response: response) handlePersistAuthenticationResponse(response: response)
default: default:
break fatalError()
} }
completionHandler()
} }
func handleUpdateResponse(response: UNNotificationResponse) { func handleUpdateResponse(response: UNNotificationResponse) {
state.withLock { state in guard let update = release else { return }
guard let update = state.release else { return } switch response.actionIdentifier {
switch response.actionIdentifier { case Notifier.Constants.updateActionIdentitifier, UNNotificationDefaultActionIdentifier:
case Notifier.Constants.updateActionIdentitifier, UNNotificationDefaultActionIdentifier: NSWorkspace.shared.open(update.html_url)
NSWorkspace.shared.open(update.html_url) case Notifier.Constants.ignoreActionIdentitifier:
case Notifier.Constants.ignoreActionIdentitifier: ignore?(update)
state.ignore?(update) default:
default: fatalError()
fatalError()
}
} }
} }
func handlePersistAuthenticationResponse(response: UNNotificationResponse) async { func handlePersistAuthenticationResponse(response: UNNotificationResponse) {
// let (secret, store, persistOptions, callback): (AnySecret?, AnySecretStore?, TimeInterval?, State.PersistAuthentication?) = state.withLock { state in guard let secretID = response.notification.request.content.userInfo[Notifier.Constants.persistSecretIDKey] as? String, let secret = pendingPersistableSecrets[secretID],
// guard let secretID = response.notification.request.content.userInfo[Notifier.Constants.persistSecretIDKey] as? String, let secret = state.pendingPersistableSecrets[secretID], let storeID = response.notification.request.content.userInfo[Notifier.Constants.persistStoreIDKey] as? String, let store = pendingPersistableStores[storeID]
// let storeID = response.notification.request.content.userInfo[Notifier.Constants.persistStoreIDKey] as? String, let store = state.pendingPersistableStores[storeID] else { return }
// else { return (nil, nil, nil, nil) } pendingPersistableSecrets[secretID] = nil
// state.pendingPersistableSecrets[secretID] = nil persistAuthentication?(secret, store, persistOptions[response.actionIdentifier])
// return (secret, store, state.persistOptions[response.actionIdentifier], state.persistAuthentication)
// }
// guard let secret, let store, let persistOptions else { return }
// await callback?(secret, store, persistOptions)
} }
func userNotificationCenter(_ center: UNUserNotificationCenter, willPresent notification: UNNotification, withCompletionHandler completionHandler: @escaping (UNNotificationPresentationOptions) -> Void) {
func userNotificationCenter(_ center: UNUserNotificationCenter, willPresent notification: UNNotification) async -> UNNotificationPresentationOptions { completionHandler([.list, .banner])
[.list, .banner]
} }
} }

View File

@ -3,7 +3,7 @@
archiveVersion = 1; archiveVersion = 1;
classes = { classes = {
}; };
objectVersion = 54; objectVersion = 52;
objects = { objects = {
/* Begin PBXBuildFile section */ /* Begin PBXBuildFile section */
@ -18,7 +18,8 @@
5003EF612780081600DF2006 /* SmartCardSecretKit in Frameworks */ = {isa = PBXBuildFile; productRef = 5003EF602780081600DF2006 /* SmartCardSecretKit */; }; 5003EF612780081600DF2006 /* SmartCardSecretKit in Frameworks */ = {isa = PBXBuildFile; productRef = 5003EF602780081600DF2006 /* SmartCardSecretKit */; };
5003EF632780081B00DF2006 /* SecureEnclaveSecretKit in Frameworks */ = {isa = PBXBuildFile; productRef = 5003EF622780081B00DF2006 /* SecureEnclaveSecretKit */; }; 5003EF632780081B00DF2006 /* SecureEnclaveSecretKit in Frameworks */ = {isa = PBXBuildFile; productRef = 5003EF622780081B00DF2006 /* SecureEnclaveSecretKit */; };
5003EF652780081B00DF2006 /* SmartCardSecretKit in Frameworks */ = {isa = PBXBuildFile; productRef = 5003EF642780081B00DF2006 /* SmartCardSecretKit */; }; 5003EF652780081B00DF2006 /* SmartCardSecretKit in Frameworks */ = {isa = PBXBuildFile; productRef = 5003EF642780081B00DF2006 /* SmartCardSecretKit */; };
500B93C32B478D8400E157DE /* Localizable.xcstrings in Resources */ = {isa = PBXBuildFile; fileRef = 500B93C22B478D8400E157DE /* Localizable.xcstrings */; }; 500ED3D427B7934A00A6DC28 /* UpdaterProtocol.swift in Sources */ = {isa = PBXBuildFile; fileRef = 5088065927B4A5E40090BD57 /* UpdaterProtocol.swift */; };
500ED3DA27B797EE00A6DC28 /* Z72PRUAWF6.com.maxgoedjen.SecretiveUpdater.app in CopyFiles */ = {isa = PBXBuildFile; fileRef = 5081F6D027B790DD0094B82D /* Z72PRUAWF6.com.maxgoedjen.SecretiveUpdater.app */; settings = {ATTRIBUTES = (RemoveHeadersOnCopy, ); }; };
501421622781262300BBAA70 /* Brief in Frameworks */ = {isa = PBXBuildFile; productRef = 501421612781262300BBAA70 /* Brief */; }; 501421622781262300BBAA70 /* Brief in Frameworks */ = {isa = PBXBuildFile; productRef = 501421612781262300BBAA70 /* Brief */; };
501421652781268000BBAA70 /* SecretAgent.app in CopyFiles */ = {isa = PBXBuildFile; fileRef = 50A3B78A24026B7500D209EA /* SecretAgent.app */; settings = {ATTRIBUTES = (RemoveHeadersOnCopy, ); }; }; 501421652781268000BBAA70 /* SecretAgent.app in CopyFiles */ = {isa = PBXBuildFile; fileRef = 50A3B78A24026B7500D209EA /* SecretAgent.app */; settings = {ATTRIBUTES = (RemoveHeadersOnCopy, ); }; };
50153E20250AFCB200525160 /* UpdateView.swift in Sources */ = {isa = PBXBuildFile; fileRef = 50153E1F250AFCB200525160 /* UpdateView.swift */; }; 50153E20250AFCB200525160 /* UpdateView.swift in Sources */ = {isa = PBXBuildFile; fileRef = 50153E1F250AFCB200525160 /* UpdateView.swift */; };
@ -30,14 +31,21 @@
50617D8523FCE48E0099B055 /* ContentView.swift in Sources */ = {isa = PBXBuildFile; fileRef = 50617D8423FCE48E0099B055 /* ContentView.swift */; }; 50617D8523FCE48E0099B055 /* ContentView.swift in Sources */ = {isa = PBXBuildFile; fileRef = 50617D8423FCE48E0099B055 /* ContentView.swift */; };
50617D8723FCE48E0099B055 /* Assets.xcassets in Resources */ = {isa = PBXBuildFile; fileRef = 50617D8623FCE48E0099B055 /* Assets.xcassets */; }; 50617D8723FCE48E0099B055 /* Assets.xcassets in Resources */ = {isa = PBXBuildFile; fileRef = 50617D8623FCE48E0099B055 /* Assets.xcassets */; };
50617D8A23FCE48E0099B055 /* Preview Assets.xcassets in Resources */ = {isa = PBXBuildFile; fileRef = 50617D8923FCE48E0099B055 /* Preview Assets.xcassets */; }; 50617D8A23FCE48E0099B055 /* Preview Assets.xcassets in Resources */ = {isa = PBXBuildFile; fileRef = 50617D8923FCE48E0099B055 /* Preview Assets.xcassets */; };
50617D9923FCE48E0099B055 /* SecretiveTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 50617D9823FCE48E0099B055 /* SecretiveTests.swift */; };
50617DD223FCEFA90099B055 /* PreviewStore.swift in Sources */ = {isa = PBXBuildFile; fileRef = 50617DD123FCEFA90099B055 /* PreviewStore.swift */; }; 50617DD223FCEFA90099B055 /* PreviewStore.swift in Sources */ = {isa = PBXBuildFile; fileRef = 50617DD123FCEFA90099B055 /* PreviewStore.swift */; };
5065E313295517C500E16645 /* ToolbarButtonStyle.swift in Sources */ = {isa = PBXBuildFile; fileRef = 5065E312295517C500E16645 /* ToolbarButtonStyle.swift */; };
5066A6C22516F303004B5A36 /* SetupView.swift in Sources */ = {isa = PBXBuildFile; fileRef = 5066A6C12516F303004B5A36 /* SetupView.swift */; }; 5066A6C22516F303004B5A36 /* SetupView.swift in Sources */ = {isa = PBXBuildFile; fileRef = 5066A6C12516F303004B5A36 /* SetupView.swift */; };
5066A6C82516FE6E004B5A36 /* CopyableView.swift in Sources */ = {isa = PBXBuildFile; fileRef = 5066A6C72516FE6E004B5A36 /* CopyableView.swift */; }; 5066A6C82516FE6E004B5A36 /* CopyableView.swift in Sources */ = {isa = PBXBuildFile; fileRef = 5066A6C72516FE6E004B5A36 /* CopyableView.swift */; };
5066A6F7251829B1004B5A36 /* ShellConfigurationController.swift in Sources */ = {isa = PBXBuildFile; fileRef = 5066A6F6251829B1004B5A36 /* ShellConfigurationController.swift */; }; 5066A6F7251829B1004B5A36 /* ShellConfigurationController.swift in Sources */ = {isa = PBXBuildFile; fileRef = 5066A6F6251829B1004B5A36 /* ShellConfigurationController.swift */; };
506772C72424784600034DED /* Credits.rtf in Resources */ = {isa = PBXBuildFile; fileRef = 506772C62424784600034DED /* Credits.rtf */; }; 506772C72424784600034DED /* Credits.rtf in Resources */ = {isa = PBXBuildFile; fileRef = 506772C62424784600034DED /* Credits.rtf */; };
506772C92425BB8500034DED /* NoStoresView.swift in Sources */ = {isa = PBXBuildFile; fileRef = 506772C82425BB8500034DED /* NoStoresView.swift */; }; 506772C92425BB8500034DED /* NoStoresView.swift in Sources */ = {isa = PBXBuildFile; fileRef = 506772C82425BB8500034DED /* NoStoresView.swift */; };
5079BA0F250F29BF00EA86F4 /* StoreListView.swift in Sources */ = {isa = PBXBuildFile; fileRef = 5079BA0E250F29BF00EA86F4 /* StoreListView.swift */; }; 5079BA0F250F29BF00EA86F4 /* StoreListView.swift in Sources */ = {isa = PBXBuildFile; fileRef = 5079BA0E250F29BF00EA86F4 /* StoreListView.swift */; };
5081F6D327B790DD0094B82D /* main.swift in Sources */ = {isa = PBXBuildFile; fileRef = 5081F6D227B790DD0094B82D /* main.swift */; };
5081F6D727B790DE0094B82D /* Assets.xcassets in Resources */ = {isa = PBXBuildFile; fileRef = 5081F6D627B790DE0094B82D /* Assets.xcassets */; };
5081F6E027B791110094B82D /* UpdaterProtocol.swift in Sources */ = {isa = PBXBuildFile; fileRef = 5088065927B4A5E40090BD57 /* UpdaterProtocol.swift */; };
5081F6E127B791110094B82D /* Updater.swift in Sources */ = {isa = PBXBuildFile; fileRef = 5088065B27B4A6240090BD57 /* Updater.swift */; };
5081F6E327B791620094B82D /* Brief in Frameworks */ = {isa = PBXBuildFile; productRef = 5081F6E227B791620094B82D /* Brief */; };
5081F70027B792150094B82D /* Main.storyboard in Resources */ = {isa = PBXBuildFile; fileRef = 5081F6FF27B792150094B82D /* Main.storyboard */; };
5088068F27B4A6FF0090BD57 /* UpdaterCommunicationController.swift in Sources */ = {isa = PBXBuildFile; fileRef = 5088068E27B4A6FF0090BD57 /* UpdaterCommunicationController.swift */; };
508A58AA241E06B40069DC07 /* PreviewUpdater.swift in Sources */ = {isa = PBXBuildFile; fileRef = 508A58A9241E06B40069DC07 /* PreviewUpdater.swift */; }; 508A58AA241E06B40069DC07 /* PreviewUpdater.swift in Sources */ = {isa = PBXBuildFile; fileRef = 508A58A9241E06B40069DC07 /* PreviewUpdater.swift */; };
508A58B3241ED2180069DC07 /* AgentStatusChecker.swift in Sources */ = {isa = PBXBuildFile; fileRef = 508A58B2241ED2180069DC07 /* AgentStatusChecker.swift */; }; 508A58B3241ED2180069DC07 /* AgentStatusChecker.swift in Sources */ = {isa = PBXBuildFile; fileRef = 508A58B2241ED2180069DC07 /* AgentStatusChecker.swift */; };
508A58B5241ED48F0069DC07 /* PreviewAgentStatusChecker.swift in Sources */ = {isa = PBXBuildFile; fileRef = 508A58B4241ED48F0069DC07 /* PreviewAgentStatusChecker.swift */; }; 508A58B5241ED48F0069DC07 /* PreviewAgentStatusChecker.swift in Sources */ = {isa = PBXBuildFile; fileRef = 508A58B4241ED48F0069DC07 /* PreviewAgentStatusChecker.swift */; };
@ -51,10 +59,23 @@
50B8550D24138C4F009958AC /* DeleteSecretView.swift in Sources */ = {isa = PBXBuildFile; fileRef = 50B8550C24138C4F009958AC /* DeleteSecretView.swift */; }; 50B8550D24138C4F009958AC /* DeleteSecretView.swift in Sources */ = {isa = PBXBuildFile; fileRef = 50B8550C24138C4F009958AC /* DeleteSecretView.swift */; };
50BB046B2418AAAE00D6E079 /* EmptyStoreView.swift in Sources */ = {isa = PBXBuildFile; fileRef = 50BB046A2418AAAE00D6E079 /* EmptyStoreView.swift */; }; 50BB046B2418AAAE00D6E079 /* EmptyStoreView.swift in Sources */ = {isa = PBXBuildFile; fileRef = 50BB046A2418AAAE00D6E079 /* EmptyStoreView.swift */; };
50C385A52407A76D00AF2719 /* SecretDetailView.swift in Sources */ = {isa = PBXBuildFile; fileRef = 50C385A42407A76D00AF2719 /* SecretDetailView.swift */; }; 50C385A52407A76D00AF2719 /* SecretDetailView.swift in Sources */ = {isa = PBXBuildFile; fileRef = 50C385A42407A76D00AF2719 /* SecretDetailView.swift */; };
50E9CF422B51D596004AB36D /* Localizable.xcstrings in Resources */ = {isa = PBXBuildFile; fileRef = 500B93C22B478D8400E157DE /* Localizable.xcstrings */; };
/* End PBXBuildFile section */ /* End PBXBuildFile section */
/* Begin PBXContainerItemProxy section */ /* Begin PBXContainerItemProxy section */
500ED3D627B796C800A6DC28 /* PBXContainerItemProxy */ = {
isa = PBXContainerItemProxy;
containerPortal = 50617D7723FCE48D0099B055 /* Project object */;
proxyType = 1;
remoteGlobalIDString = 5081F6CF27B790DD0094B82D;
remoteInfo = SecretiveUpdater;
};
500ED3D827B7978700A6DC28 /* PBXContainerItemProxy */ = {
isa = PBXContainerItemProxy;
containerPortal = 50617D7723FCE48D0099B055 /* Project object */;
proxyType = 1;
remoteGlobalIDString = 5081F6CF27B790DD0094B82D;
remoteInfo = SecretiveUpdater;
};
50142166278126B500BBAA70 /* PBXContainerItemProxy */ = { 50142166278126B500BBAA70 /* PBXContainerItemProxy */ = {
isa = PBXContainerItemProxy; isa = PBXContainerItemProxy;
containerPortal = 50617D7723FCE48D0099B055 /* Project object */; containerPortal = 50617D7723FCE48D0099B055 /* Project object */;
@ -62,6 +83,13 @@
remoteGlobalIDString = 50A3B78924026B7500D209EA; remoteGlobalIDString = 50A3B78924026B7500D209EA;
remoteInfo = SecretAgent; remoteInfo = SecretAgent;
}; };
50617D9523FCE48E0099B055 /* PBXContainerItemProxy */ = {
isa = PBXContainerItemProxy;
containerPortal = 50617D7723FCE48D0099B055 /* Project object */;
proxyType = 1;
remoteGlobalIDString = 50617D7E23FCE48D0099B055;
remoteInfo = Secretive;
};
/* End PBXContainerItemProxy section */ /* End PBXContainerItemProxy section */
/* Begin PBXCopyFilesBuildPhase section */ /* Begin PBXCopyFilesBuildPhase section */
@ -91,6 +119,7 @@
dstPath = Contents/Library/LoginItems; dstPath = Contents/Library/LoginItems;
dstSubfolderSpec = 1; dstSubfolderSpec = 1;
files = ( files = (
500ED3DA27B797EE00A6DC28 /* Z72PRUAWF6.com.maxgoedjen.SecretiveUpdater.app in CopyFiles */,
501421652781268000BBAA70 /* SecretAgent.app in CopyFiles */, 501421652781268000BBAA70 /* SecretAgent.app in CopyFiles */,
); );
runOnlyForDeploymentPostprocessing = 0; runOnlyForDeploymentPostprocessing = 0;
@ -102,7 +131,6 @@
50020BAF24064869003D4025 /* AppDelegate.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = AppDelegate.swift; sourceTree = "<group>"; }; 50020BAF24064869003D4025 /* AppDelegate.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = AppDelegate.swift; sourceTree = "<group>"; };
50033AC227813F1700253856 /* BundleIDs.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = BundleIDs.swift; sourceTree = "<group>"; }; 50033AC227813F1700253856 /* BundleIDs.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = BundleIDs.swift; sourceTree = "<group>"; };
5003EF39278005C800DF2006 /* Packages */ = {isa = PBXFileReference; lastKnownFileType = wrapper; path = Packages; sourceTree = "<group>"; }; 5003EF39278005C800DF2006 /* Packages */ = {isa = PBXFileReference; lastKnownFileType = wrapper; path = Packages; sourceTree = "<group>"; };
500B93C22B478D8400E157DE /* Localizable.xcstrings */ = {isa = PBXFileReference; lastKnownFileType = text.json.xcstrings; path = Localizable.xcstrings; sourceTree = "<group>"; };
50153E1F250AFCB200525160 /* UpdateView.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = UpdateView.swift; sourceTree = "<group>"; }; 50153E1F250AFCB200525160 /* UpdateView.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = UpdateView.swift; sourceTree = "<group>"; };
50153E21250DECA300525160 /* SecretListItemView.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = SecretListItemView.swift; sourceTree = "<group>"; }; 50153E21250DECA300525160 /* SecretListItemView.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = SecretListItemView.swift; sourceTree = "<group>"; };
5018F54E24064786002EB505 /* Notifier.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = Notifier.swift; sourceTree = "<group>"; }; 5018F54E24064786002EB505 /* Notifier.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = Notifier.swift; sourceTree = "<group>"; };
@ -115,14 +143,24 @@
50617D8923FCE48E0099B055 /* Preview Assets.xcassets */ = {isa = PBXFileReference; lastKnownFileType = folder.assetcatalog; path = "Preview Assets.xcassets"; sourceTree = "<group>"; }; 50617D8923FCE48E0099B055 /* Preview Assets.xcassets */ = {isa = PBXFileReference; lastKnownFileType = folder.assetcatalog; path = "Preview Assets.xcassets"; sourceTree = "<group>"; };
50617D8E23FCE48E0099B055 /* Info.plist */ = {isa = PBXFileReference; lastKnownFileType = text.plist.xml; path = Info.plist; sourceTree = "<group>"; }; 50617D8E23FCE48E0099B055 /* Info.plist */ = {isa = PBXFileReference; lastKnownFileType = text.plist.xml; path = Info.plist; sourceTree = "<group>"; };
50617D8F23FCE48E0099B055 /* Secretive.entitlements */ = {isa = PBXFileReference; lastKnownFileType = text.plist.entitlements; path = Secretive.entitlements; sourceTree = "<group>"; }; 50617D8F23FCE48E0099B055 /* Secretive.entitlements */ = {isa = PBXFileReference; lastKnownFileType = text.plist.entitlements; path = Secretive.entitlements; sourceTree = "<group>"; };
50617D9423FCE48E0099B055 /* SecretiveTests.xctest */ = {isa = PBXFileReference; explicitFileType = wrapper.cfbundle; includeInIndex = 0; path = SecretiveTests.xctest; sourceTree = BUILT_PRODUCTS_DIR; };
50617D9823FCE48E0099B055 /* SecretiveTests.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = SecretiveTests.swift; sourceTree = "<group>"; };
50617D9A23FCE48E0099B055 /* Info.plist */ = {isa = PBXFileReference; lastKnownFileType = text.plist.xml; path = Info.plist; sourceTree = "<group>"; };
50617DD123FCEFA90099B055 /* PreviewStore.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = PreviewStore.swift; sourceTree = "<group>"; }; 50617DD123FCEFA90099B055 /* PreviewStore.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = PreviewStore.swift; sourceTree = "<group>"; };
5065E312295517C500E16645 /* ToolbarButtonStyle.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = ToolbarButtonStyle.swift; sourceTree = "<group>"; };
5066A6C12516F303004B5A36 /* SetupView.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = SetupView.swift; sourceTree = "<group>"; }; 5066A6C12516F303004B5A36 /* SetupView.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = SetupView.swift; sourceTree = "<group>"; };
5066A6C72516FE6E004B5A36 /* CopyableView.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = CopyableView.swift; sourceTree = "<group>"; }; 5066A6C72516FE6E004B5A36 /* CopyableView.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = CopyableView.swift; sourceTree = "<group>"; };
5066A6F6251829B1004B5A36 /* ShellConfigurationController.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = ShellConfigurationController.swift; sourceTree = "<group>"; }; 5066A6F6251829B1004B5A36 /* ShellConfigurationController.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = ShellConfigurationController.swift; sourceTree = "<group>"; };
506772C62424784600034DED /* Credits.rtf */ = {isa = PBXFileReference; lastKnownFileType = text.rtf; path = Credits.rtf; sourceTree = "<group>"; }; 506772C62424784600034DED /* Credits.rtf */ = {isa = PBXFileReference; lastKnownFileType = text.rtf; path = Credits.rtf; sourceTree = "<group>"; };
506772C82425BB8500034DED /* NoStoresView.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = NoStoresView.swift; sourceTree = "<group>"; }; 506772C82425BB8500034DED /* NoStoresView.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = NoStoresView.swift; sourceTree = "<group>"; };
5079BA0E250F29BF00EA86F4 /* StoreListView.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = StoreListView.swift; sourceTree = "<group>"; }; 5079BA0E250F29BF00EA86F4 /* StoreListView.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = StoreListView.swift; sourceTree = "<group>"; };
5081F6D027B790DD0094B82D /* Z72PRUAWF6.com.maxgoedjen.SecretiveUpdater.app */ = {isa = PBXFileReference; explicitFileType = wrapper.application; includeInIndex = 0; path = Z72PRUAWF6.com.maxgoedjen.SecretiveUpdater.app; sourceTree = BUILT_PRODUCTS_DIR; };
5081F6D227B790DD0094B82D /* main.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = main.swift; sourceTree = "<group>"; };
5081F6D627B790DE0094B82D /* Assets.xcassets */ = {isa = PBXFileReference; lastKnownFileType = folder.assetcatalog; path = Assets.xcassets; sourceTree = "<group>"; };
5081F6DB27B790DE0094B82D /* SecretiveUpdater.entitlements */ = {isa = PBXFileReference; lastKnownFileType = text.plist.entitlements; path = SecretiveUpdater.entitlements; sourceTree = "<group>"; };
5081F6FF27B792150094B82D /* Main.storyboard */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = file.storyboard; path = Main.storyboard; sourceTree = "<group>"; };
5088065927B4A5E40090BD57 /* UpdaterProtocol.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = UpdaterProtocol.swift; sourceTree = "<group>"; };
5088065B27B4A6240090BD57 /* Updater.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = Updater.swift; sourceTree = "<group>"; };
5088068E27B4A6FF0090BD57 /* UpdaterCommunicationController.swift */ = {isa = PBXFileReference; fileEncoding = 4; indentWidth = 5; lastKnownFileType = sourcecode.swift; path = UpdaterCommunicationController.swift; sourceTree = "<group>"; };
508A58A9241E06B40069DC07 /* PreviewUpdater.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = PreviewUpdater.swift; sourceTree = "<group>"; }; 508A58A9241E06B40069DC07 /* PreviewUpdater.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = PreviewUpdater.swift; sourceTree = "<group>"; };
508A58AB241E121B0069DC07 /* Config.xcconfig */ = {isa = PBXFileReference; lastKnownFileType = text.xcconfig; path = Config.xcconfig; sourceTree = "<group>"; }; 508A58AB241E121B0069DC07 /* Config.xcconfig */ = {isa = PBXFileReference; lastKnownFileType = text.xcconfig; path = Config.xcconfig; sourceTree = "<group>"; };
508A58B2241ED2180069DC07 /* AgentStatusChecker.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = AgentStatusChecker.swift; sourceTree = "<group>"; }; 508A58B2241ED2180069DC07 /* AgentStatusChecker.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = AgentStatusChecker.swift; sourceTree = "<group>"; };
@ -155,6 +193,21 @@
); );
runOnlyForDeploymentPostprocessing = 0; runOnlyForDeploymentPostprocessing = 0;
}; };
50617D9123FCE48E0099B055 /* Frameworks */ = {
isa = PBXFrameworksBuildPhase;
buildActionMask = 2147483647;
files = (
);
runOnlyForDeploymentPostprocessing = 0;
};
5081F6CD27B790DD0094B82D /* Frameworks */ = {
isa = PBXFrameworksBuildPhase;
buildActionMask = 2147483647;
files = (
5081F6E327B791620094B82D /* Brief in Frameworks */,
);
runOnlyForDeploymentPostprocessing = 0;
};
50A3B78724026B7500D209EA /* Frameworks */ = { 50A3B78724026B7500D209EA /* Frameworks */ = {
isa = PBXFrameworksBuildPhase; isa = PBXFrameworksBuildPhase;
buildActionMask = 2147483647; buildActionMask = 2147483647;
@ -183,8 +236,10 @@
children = ( children = (
5003EF39278005C800DF2006 /* Packages */, 5003EF39278005C800DF2006 /* Packages */,
50617D8123FCE48E0099B055 /* Secretive */, 50617D8123FCE48E0099B055 /* Secretive */,
50617D9723FCE48E0099B055 /* SecretiveTests */,
50A3B78B24026B7500D209EA /* SecretAgent */, 50A3B78B24026B7500D209EA /* SecretAgent */,
508A58AF241E144C0069DC07 /* Config */, 508A58AF241E144C0069DC07 /* Config */,
5081F6D127B790DD0094B82D /* SecretiveUpdater */,
50617D8023FCE48E0099B055 /* Products */, 50617D8023FCE48E0099B055 /* Products */,
5099A08B240243730062B6F2 /* Frameworks */, 5099A08B240243730062B6F2 /* Frameworks */,
); );
@ -194,7 +249,9 @@
isa = PBXGroup; isa = PBXGroup;
children = ( children = (
50617D7F23FCE48E0099B055 /* Secretive.app */, 50617D7F23FCE48E0099B055 /* Secretive.app */,
50617D9423FCE48E0099B055 /* SecretiveTests.xctest */,
50A3B78A24026B7500D209EA /* SecretAgent.app */, 50A3B78A24026B7500D209EA /* SecretAgent.app */,
5081F6D027B790DD0094B82D /* Z72PRUAWF6.com.maxgoedjen.SecretiveUpdater.app */,
); );
name = Products; name = Products;
sourceTree = "<group>"; sourceTree = "<group>";
@ -211,7 +268,6 @@
508BF28D25B4F005009EFB7E /* InternetAccessPolicy.plist */, 508BF28D25B4F005009EFB7E /* InternetAccessPolicy.plist */,
50617D8F23FCE48E0099B055 /* Secretive.entitlements */, 50617D8F23FCE48E0099B055 /* Secretive.entitlements */,
506772C62424784600034DED /* Credits.rtf */, 506772C62424784600034DED /* Credits.rtf */,
500B93C22B478D8400E157DE /* Localizable.xcstrings */,
50617D8823FCE48E0099B055 /* Preview Content */, 50617D8823FCE48E0099B055 /* Preview Content */,
); );
path = Secretive; path = Secretive;
@ -228,6 +284,28 @@
path = "Preview Content"; path = "Preview Content";
sourceTree = "<group>"; sourceTree = "<group>";
}; };
50617D9723FCE48E0099B055 /* SecretiveTests */ = {
isa = PBXGroup;
children = (
50617D9823FCE48E0099B055 /* SecretiveTests.swift */,
50617D9A23FCE48E0099B055 /* Info.plist */,
);
path = SecretiveTests;
sourceTree = "<group>";
};
5081F6D127B790DD0094B82D /* SecretiveUpdater */ = {
isa = PBXGroup;
children = (
5081F6D227B790DD0094B82D /* main.swift */,
5088065927B4A5E40090BD57 /* UpdaterProtocol.swift */,
5088065B27B4A6240090BD57 /* Updater.swift */,
5081F6FF27B792150094B82D /* Main.storyboard */,
5081F6D627B790DE0094B82D /* Assets.xcassets */,
5081F6DB27B790DE0094B82D /* SecretiveUpdater.entitlements */,
);
path = SecretiveUpdater;
sourceTree = "<group>";
};
508A58AF241E144C0069DC07 /* Config */ = { 508A58AF241E144C0069DC07 /* Config */ = {
isa = PBXGroup; isa = PBXGroup;
children = ( children = (
@ -241,7 +319,6 @@
isa = PBXGroup; isa = PBXGroup;
children = ( children = (
50617D8423FCE48E0099B055 /* ContentView.swift */, 50617D8423FCE48E0099B055 /* ContentView.swift */,
5065E312295517C500E16645 /* ToolbarButtonStyle.swift */,
5079BA0E250F29BF00EA86F4 /* StoreListView.swift */, 5079BA0E250F29BF00EA86F4 /* StoreListView.swift */,
50153E21250DECA300525160 /* SecretListItemView.swift */, 50153E21250DECA300525160 /* SecretListItemView.swift */,
50C385A42407A76D00AF2719 /* SecretDetailView.swift */, 50C385A42407A76D00AF2719 /* SecretDetailView.swift */,
@ -260,11 +337,12 @@
508A58B1241ED1EA0069DC07 /* Controllers */ = { 508A58B1241ED1EA0069DC07 /* Controllers */ = {
isa = PBXGroup; isa = PBXGroup;
children = ( children = (
5088068E27B4A6FF0090BD57 /* UpdaterCommunicationController.swift */,
508A58B2241ED2180069DC07 /* AgentStatusChecker.swift */, 508A58B2241ED2180069DC07 /* AgentStatusChecker.swift */,
5091D2BB25183B830049FD9B /* ApplicationDirectoryController.swift */, 5091D2BB25183B830049FD9B /* ApplicationDirectoryController.swift */,
50571E0224393C2600F76F6C /* JustUpdatedChecker.swift */, 50571E0224393C2600F76F6C /* JustUpdatedChecker.swift */,
50571E0424393D1500F76F6C /* LaunchAgentController.swift */,
5066A6F6251829B1004B5A36 /* ShellConfigurationController.swift */, 5066A6F6251829B1004B5A36 /* ShellConfigurationController.swift */,
50571E0424393D1500F76F6C /* LaunchAgentController.swift */,
); );
path = Controllers; path = Controllers;
sourceTree = "<group>"; sourceTree = "<group>";
@ -316,6 +394,8 @@
); );
dependencies = ( dependencies = (
50142167278126B500BBAA70 /* PBXTargetDependency */, 50142167278126B500BBAA70 /* PBXTargetDependency */,
500ED3D727B796C800A6DC28 /* PBXTargetDependency */,
500ED3D927B7978700A6DC28 /* PBXTargetDependency */,
); );
name = Secretive; name = Secretive;
packageProductDependencies = ( packageProductDependencies = (
@ -328,6 +408,44 @@
productReference = 50617D7F23FCE48E0099B055 /* Secretive.app */; productReference = 50617D7F23FCE48E0099B055 /* Secretive.app */;
productType = "com.apple.product-type.application"; productType = "com.apple.product-type.application";
}; };
50617D9323FCE48E0099B055 /* SecretiveTests */ = {
isa = PBXNativeTarget;
buildConfigurationList = 50617DA023FCE48E0099B055 /* Build configuration list for PBXNativeTarget "SecretiveTests" */;
buildPhases = (
50617D9023FCE48E0099B055 /* Sources */,
50617D9123FCE48E0099B055 /* Frameworks */,
50617D9223FCE48E0099B055 /* Resources */,
);
buildRules = (
);
dependencies = (
50617D9623FCE48E0099B055 /* PBXTargetDependency */,
);
name = SecretiveTests;
productName = SecretiveTests;
productReference = 50617D9423FCE48E0099B055 /* SecretiveTests.xctest */;
productType = "com.apple.product-type.bundle.unit-test";
};
5081F6CF27B790DD0094B82D /* SecretiveUpdater */ = {
isa = PBXNativeTarget;
buildConfigurationList = 5081F6DC27B790DE0094B82D /* Build configuration list for PBXNativeTarget "SecretiveUpdater" */;
buildPhases = (
5081F6CC27B790DD0094B82D /* Sources */,
5081F6CD27B790DD0094B82D /* Frameworks */,
5081F6CE27B790DD0094B82D /* Resources */,
);
buildRules = (
);
dependencies = (
);
name = SecretiveUpdater;
packageProductDependencies = (
5081F6E227B791620094B82D /* Brief */,
);
productName = SecretiveUpdater;
productReference = 5081F6D027B790DD0094B82D /* Z72PRUAWF6.com.maxgoedjen.SecretiveUpdater.app */;
productType = "com.apple.product-type.application";
};
50A3B78924026B7500D209EA /* SecretAgent */ = { 50A3B78924026B7500D209EA /* SecretAgent */ = {
isa = PBXNativeTarget; isa = PBXNativeTarget;
buildConfigurationList = 50A3B79A24026B7600D209EA /* Build configuration list for PBXNativeTarget "SecretAgent" */; buildConfigurationList = 50A3B79A24026B7600D209EA /* Build configuration list for PBXNativeTarget "SecretAgent" */;
@ -359,13 +477,20 @@
50617D7723FCE48D0099B055 /* Project object */ = { 50617D7723FCE48D0099B055 /* Project object */ = {
isa = PBXProject; isa = PBXProject;
attributes = { attributes = {
LastSwiftUpdateCheck = 1220; LastSwiftUpdateCheck = 1330;
LastUpgradeCheck = 1320; LastUpgradeCheck = 1320;
ORGANIZATIONNAME = "Max Goedjen"; ORGANIZATIONNAME = "Max Goedjen";
TargetAttributes = { TargetAttributes = {
50617D7E23FCE48D0099B055 = { 50617D7E23FCE48D0099B055 = {
CreatedOnToolsVersion = 11.3; CreatedOnToolsVersion = 11.3;
}; };
50617D9323FCE48E0099B055 = {
CreatedOnToolsVersion = 11.3;
TestTargetID = 50617D7E23FCE48D0099B055;
};
5081F6CF27B790DD0094B82D = {
CreatedOnToolsVersion = 13.3;
};
50A3B78924026B7500D209EA = { 50A3B78924026B7500D209EA = {
CreatedOnToolsVersion = 11.4; CreatedOnToolsVersion = 11.4;
}; };
@ -378,13 +503,6 @@
knownRegions = ( knownRegions = (
en, en,
Base, Base,
it,
fr,
de,
"pt-BR",
fi,
ko,
ca,
); );
mainGroup = 50617D7623FCE48D0099B055; mainGroup = 50617D7623FCE48D0099B055;
productRefGroup = 50617D8023FCE48E0099B055 /* Products */; productRefGroup = 50617D8023FCE48E0099B055 /* Products */;
@ -392,7 +510,9 @@
projectRoot = ""; projectRoot = "";
targets = ( targets = (
50617D7E23FCE48D0099B055 /* Secretive */, 50617D7E23FCE48D0099B055 /* Secretive */,
50617D9323FCE48E0099B055 /* SecretiveTests */,
50A3B78924026B7500D209EA /* SecretAgent */, 50A3B78924026B7500D209EA /* SecretAgent */,
5081F6CF27B790DD0094B82D /* SecretiveUpdater */,
); );
}; };
/* End PBXProject section */ /* End PBXProject section */
@ -403,19 +523,33 @@
buildActionMask = 2147483647; buildActionMask = 2147483647;
files = ( files = (
50617D8A23FCE48E0099B055 /* Preview Assets.xcassets in Resources */, 50617D8A23FCE48E0099B055 /* Preview Assets.xcassets in Resources */,
500B93C32B478D8400E157DE /* Localizable.xcstrings in Resources */,
50617D8723FCE48E0099B055 /* Assets.xcassets in Resources */, 50617D8723FCE48E0099B055 /* Assets.xcassets in Resources */,
506772C72424784600034DED /* Credits.rtf in Resources */, 506772C72424784600034DED /* Credits.rtf in Resources */,
508BF28E25B4F005009EFB7E /* InternetAccessPolicy.plist in Resources */, 508BF28E25B4F005009EFB7E /* InternetAccessPolicy.plist in Resources */,
); );
runOnlyForDeploymentPostprocessing = 0; runOnlyForDeploymentPostprocessing = 0;
}; };
50617D9223FCE48E0099B055 /* Resources */ = {
isa = PBXResourcesBuildPhase;
buildActionMask = 2147483647;
files = (
);
runOnlyForDeploymentPostprocessing = 0;
};
5081F6CE27B790DD0094B82D /* Resources */ = {
isa = PBXResourcesBuildPhase;
buildActionMask = 2147483647;
files = (
5081F6D727B790DE0094B82D /* Assets.xcassets in Resources */,
5081F70027B792150094B82D /* Main.storyboard in Resources */,
);
runOnlyForDeploymentPostprocessing = 0;
};
50A3B78824026B7500D209EA /* Resources */ = { 50A3B78824026B7500D209EA /* Resources */ = {
isa = PBXResourcesBuildPhase; isa = PBXResourcesBuildPhase;
buildActionMask = 2147483647; buildActionMask = 2147483647;
files = ( files = (
50A3B79724026B7600D209EA /* Main.storyboard in Resources */, 50A3B79724026B7600D209EA /* Main.storyboard in Resources */,
50E9CF422B51D596004AB36D /* Localizable.xcstrings in Resources */,
50A3B79424026B7600D209EA /* Preview Assets.xcassets in Resources */, 50A3B79424026B7600D209EA /* Preview Assets.xcassets in Resources */,
50A3B79124026B7600D209EA /* Assets.xcassets in Resources */, 50A3B79124026B7600D209EA /* Assets.xcassets in Resources */,
508BF2AA25B4F1CB009EFB7E /* InternetAccessPolicy.plist in Resources */, 508BF2AA25B4F1CB009EFB7E /* InternetAccessPolicy.plist in Resources */,
@ -432,11 +566,11 @@
2C4A9D2F2636FFD3008CC8E2 /* RenameSecretView.swift in Sources */, 2C4A9D2F2636FFD3008CC8E2 /* RenameSecretView.swift in Sources */,
5091D2BC25183B830049FD9B /* ApplicationDirectoryController.swift in Sources */, 5091D2BC25183B830049FD9B /* ApplicationDirectoryController.swift in Sources */,
5066A6C22516F303004B5A36 /* SetupView.swift in Sources */, 5066A6C22516F303004B5A36 /* SetupView.swift in Sources */,
5065E313295517C500E16645 /* ToolbarButtonStyle.swift in Sources */,
50617D8523FCE48E0099B055 /* ContentView.swift in Sources */, 50617D8523FCE48E0099B055 /* ContentView.swift in Sources */,
50571E0324393C2600F76F6C /* JustUpdatedChecker.swift in Sources */, 50571E0324393C2600F76F6C /* JustUpdatedChecker.swift in Sources */,
5079BA0F250F29BF00EA86F4 /* StoreListView.swift in Sources */, 5079BA0F250F29BF00EA86F4 /* StoreListView.swift in Sources */,
50617DD223FCEFA90099B055 /* PreviewStore.swift in Sources */, 50617DD223FCEFA90099B055 /* PreviewStore.swift in Sources */,
500ED3D427B7934A00A6DC28 /* UpdaterProtocol.swift in Sources */,
5066A6F7251829B1004B5A36 /* ShellConfigurationController.swift in Sources */, 5066A6F7251829B1004B5A36 /* ShellConfigurationController.swift in Sources */,
50033AC327813F1700253856 /* BundleIDs.swift in Sources */, 50033AC327813F1700253856 /* BundleIDs.swift in Sources */,
508A58B3241ED2180069DC07 /* AgentStatusChecker.swift in Sources */, 508A58B3241ED2180069DC07 /* AgentStatusChecker.swift in Sources */,
@ -445,6 +579,7 @@
50153E20250AFCB200525160 /* UpdateView.swift in Sources */, 50153E20250AFCB200525160 /* UpdateView.swift in Sources */,
50571E0524393D1500F76F6C /* LaunchAgentController.swift in Sources */, 50571E0524393D1500F76F6C /* LaunchAgentController.swift in Sources */,
5066A6C82516FE6E004B5A36 /* CopyableView.swift in Sources */, 5066A6C82516FE6E004B5A36 /* CopyableView.swift in Sources */,
5088068F27B4A6FF0090BD57 /* UpdaterCommunicationController.swift in Sources */,
50B8550D24138C4F009958AC /* DeleteSecretView.swift in Sources */, 50B8550D24138C4F009958AC /* DeleteSecretView.swift in Sources */,
50BB046B2418AAAE00D6E079 /* EmptyStoreView.swift in Sources */, 50BB046B2418AAAE00D6E079 /* EmptyStoreView.swift in Sources */,
50617D8323FCE48E0099B055 /* App.swift in Sources */, 50617D8323FCE48E0099B055 /* App.swift in Sources */,
@ -455,6 +590,24 @@
); );
runOnlyForDeploymentPostprocessing = 0; runOnlyForDeploymentPostprocessing = 0;
}; };
50617D9023FCE48E0099B055 /* Sources */ = {
isa = PBXSourcesBuildPhase;
buildActionMask = 2147483647;
files = (
50617D9923FCE48E0099B055 /* SecretiveTests.swift in Sources */,
);
runOnlyForDeploymentPostprocessing = 0;
};
5081F6CC27B790DD0094B82D /* Sources */ = {
isa = PBXSourcesBuildPhase;
buildActionMask = 2147483647;
files = (
5081F6D327B790DD0094B82D /* main.swift in Sources */,
5081F6E027B791110094B82D /* UpdaterProtocol.swift in Sources */,
5081F6E127B791110094B82D /* Updater.swift in Sources */,
);
runOnlyForDeploymentPostprocessing = 0;
};
50A3B78624026B7500D209EA /* Sources */ = { 50A3B78624026B7500D209EA /* Sources */ = {
isa = PBXSourcesBuildPhase; isa = PBXSourcesBuildPhase;
buildActionMask = 2147483647; buildActionMask = 2147483647;
@ -467,11 +620,26 @@
/* End PBXSourcesBuildPhase section */ /* End PBXSourcesBuildPhase section */
/* Begin PBXTargetDependency section */ /* Begin PBXTargetDependency section */
500ED3D727B796C800A6DC28 /* PBXTargetDependency */ = {
isa = PBXTargetDependency;
target = 5081F6CF27B790DD0094B82D /* SecretiveUpdater */;
targetProxy = 500ED3D627B796C800A6DC28 /* PBXContainerItemProxy */;
};
500ED3D927B7978700A6DC28 /* PBXTargetDependency */ = {
isa = PBXTargetDependency;
target = 5081F6CF27B790DD0094B82D /* SecretiveUpdater */;
targetProxy = 500ED3D827B7978700A6DC28 /* PBXContainerItemProxy */;
};
50142167278126B500BBAA70 /* PBXTargetDependency */ = { 50142167278126B500BBAA70 /* PBXTargetDependency */ = {
isa = PBXTargetDependency; isa = PBXTargetDependency;
target = 50A3B78924026B7500D209EA /* SecretAgent */; target = 50A3B78924026B7500D209EA /* SecretAgent */;
targetProxy = 50142166278126B500BBAA70 /* PBXContainerItemProxy */; targetProxy = 50142166278126B500BBAA70 /* PBXContainerItemProxy */;
}; };
50617D9623FCE48E0099B055 /* PBXTargetDependency */ = {
isa = PBXTargetDependency;
target = 50617D7E23FCE48D0099B055 /* Secretive */;
targetProxy = 50617D9523FCE48E0099B055 /* PBXContainerItemProxy */;
};
/* End PBXTargetDependency section */ /* End PBXTargetDependency section */
/* Begin PBXVariantGroup section */ /* Begin PBXVariantGroup section */
@ -538,18 +706,16 @@
GCC_WARN_UNINITIALIZED_AUTOS = YES_AGGRESSIVE; GCC_WARN_UNINITIALIZED_AUTOS = YES_AGGRESSIVE;
GCC_WARN_UNUSED_FUNCTION = YES; GCC_WARN_UNUSED_FUNCTION = YES;
GCC_WARN_UNUSED_VARIABLE = YES; GCC_WARN_UNUSED_VARIABLE = YES;
MACOSX_DEPLOYMENT_TARGET = 15.0; MACOSX_DEPLOYMENT_TARGET = 11.0;
MTL_ENABLE_DEBUG_INFO = INCLUDE_SOURCE; MTL_ENABLE_DEBUG_INFO = INCLUDE_SOURCE;
MTL_FAST_MATH = YES; MTL_FAST_MATH = YES;
ONLY_ACTIVE_ARCH = YES; ONLY_ACTIVE_ARCH = YES;
OTHER_SWIFT_FLAGS = ""; OTHER_SWIFT_FLAGS = "-Xfrontend -warn-concurrency -Xfrontend -enable-actor-data-race-checks";
SDKROOT = macosx; SDKROOT = macosx;
STRIP_INSTALLED_PRODUCT = NO; STRIP_INSTALLED_PRODUCT = NO;
STRIP_SWIFT_SYMBOLS = NO; STRIP_SWIFT_SYMBOLS = NO;
SWIFT_ACTIVE_COMPILATION_CONDITIONS = DEBUG; SWIFT_ACTIVE_COMPILATION_CONDITIONS = DEBUG;
SWIFT_EMIT_LOC_STRINGS = YES;
SWIFT_OPTIMIZATION_LEVEL = "-Onone"; SWIFT_OPTIMIZATION_LEVEL = "-Onone";
SWIFT_VERSION = 6.0;
}; };
name = Debug; name = Debug;
}; };
@ -599,17 +765,15 @@
GCC_WARN_UNINITIALIZED_AUTOS = YES_AGGRESSIVE; GCC_WARN_UNINITIALIZED_AUTOS = YES_AGGRESSIVE;
GCC_WARN_UNUSED_FUNCTION = YES; GCC_WARN_UNUSED_FUNCTION = YES;
GCC_WARN_UNUSED_VARIABLE = YES; GCC_WARN_UNUSED_VARIABLE = YES;
MACOSX_DEPLOYMENT_TARGET = 15.0; MACOSX_DEPLOYMENT_TARGET = 11.0;
MTL_ENABLE_DEBUG_INFO = NO; MTL_ENABLE_DEBUG_INFO = NO;
MTL_FAST_MATH = YES; MTL_FAST_MATH = YES;
OTHER_SWIFT_FLAGS = ""; OTHER_SWIFT_FLAGS = "-Xfrontend -warn-concurrency -Xfrontend -enable-actor-data-race-checks";
SDKROOT = macosx; SDKROOT = macosx;
STRIP_INSTALLED_PRODUCT = NO; STRIP_INSTALLED_PRODUCT = NO;
STRIP_SWIFT_SYMBOLS = NO; STRIP_SWIFT_SYMBOLS = NO;
SWIFT_COMPILATION_MODE = wholemodule; SWIFT_COMPILATION_MODE = wholemodule;
SWIFT_EMIT_LOC_STRINGS = YES;
SWIFT_OPTIMIZATION_LEVEL = "-O"; SWIFT_OPTIMIZATION_LEVEL = "-O";
SWIFT_VERSION = 6.0;
}; };
name = Release; name = Release;
}; };
@ -636,6 +800,7 @@
PRODUCT_BUNDLE_IDENTIFIER = com.maxgoedjen.Secretive.Host; PRODUCT_BUNDLE_IDENTIFIER = com.maxgoedjen.Secretive.Host;
PRODUCT_NAME = "$(TARGET_NAME)"; PRODUCT_NAME = "$(TARGET_NAME)";
PROVISIONING_PROFILE_SPECIFIER = ""; PROVISIONING_PROFILE_SPECIFIER = "";
SWIFT_VERSION = 5.0;
}; };
name = Debug; name = Debug;
}; };
@ -662,6 +827,139 @@
PRODUCT_BUNDLE_IDENTIFIER = com.maxgoedjen.Secretive.Host; PRODUCT_BUNDLE_IDENTIFIER = com.maxgoedjen.Secretive.Host;
PRODUCT_NAME = "$(TARGET_NAME)"; PRODUCT_NAME = "$(TARGET_NAME)";
PROVISIONING_PROFILE_SPECIFIER = "Secretive - Host"; PROVISIONING_PROFILE_SPECIFIER = "Secretive - Host";
SWIFT_VERSION = 5.0;
};
name = Release;
};
50617DA123FCE48E0099B055 /* Debug */ = {
isa = XCBuildConfiguration;
buildSettings = {
ALWAYS_EMBED_SWIFT_STANDARD_LIBRARIES = YES;
BUNDLE_LOADER = "$(TEST_HOST)";
CODE_SIGN_STYLE = Automatic;
COMBINE_HIDPI_IMAGES = YES;
DEVELOPMENT_TEAM = Z72PRUAWF6;
INFOPLIST_FILE = SecretiveTests/Info.plist;
LD_RUNPATH_SEARCH_PATHS = (
"$(inherited)",
"@executable_path/../Frameworks",
"@loader_path/../Frameworks",
);
PRODUCT_BUNDLE_IDENTIFIER = com.maxgoedjen.SecretiveTests;
PRODUCT_NAME = "$(TARGET_NAME)";
SWIFT_VERSION = 5.0;
TEST_HOST = "$(BUILT_PRODUCTS_DIR)/Secretive.app/Contents/MacOS/Secretive";
};
name = Debug;
};
50617DA223FCE48E0099B055 /* Release */ = {
isa = XCBuildConfiguration;
buildSettings = {
ALWAYS_EMBED_SWIFT_STANDARD_LIBRARIES = YES;
BUNDLE_LOADER = "$(TEST_HOST)";
CODE_SIGN_STYLE = Automatic;
COMBINE_HIDPI_IMAGES = YES;
DEVELOPMENT_TEAM = Z72PRUAWF6;
INFOPLIST_FILE = SecretiveTests/Info.plist;
LD_RUNPATH_SEARCH_PATHS = (
"$(inherited)",
"@executable_path/../Frameworks",
"@loader_path/../Frameworks",
);
PRODUCT_BUNDLE_IDENTIFIER = com.maxgoedjen.SecretiveTests;
PRODUCT_NAME = "$(TARGET_NAME)";
SWIFT_VERSION = 5.0;
TEST_HOST = "$(BUILT_PRODUCTS_DIR)/Secretive.app/Contents/MacOS/Secretive";
};
name = Release;
};
5081F6DD27B790DE0094B82D /* Debug */ = {
isa = XCBuildConfiguration;
buildSettings = {
ASSETCATALOG_COMPILER_APPICON_NAME = AppIcon;
ASSETCATALOG_COMPILER_GLOBAL_ACCENT_COLOR_NAME = AccentColor;
CLANG_CXX_LANGUAGE_STANDARD = "gnu++17";
CODE_SIGN_ENTITLEMENTS = SecretiveUpdater/SecretiveUpdater.entitlements;
CODE_SIGN_STYLE = Automatic;
COMBINE_HIDPI_IMAGES = YES;
CURRENT_PROJECT_VERSION = 1;
DEVELOPMENT_TEAM = Z72PRUAWF6;
ENABLE_HARDENED_RUNTIME = YES;
GENERATE_INFOPLIST_FILE = YES;
INFOPLIST_FILE = SecretiveUpdater/Info.plist;
INFOPLIST_KEY_NSHumanReadableCopyright = "Copyright © 2022 Max Goedjen. All rights reserved.";
INFOPLIST_KEY_NSMainStoryboardFile = Main;
INFOPLIST_KEY_NSPrincipalClass = NSApplication;
LD_RUNPATH_SEARCH_PATHS = (
"$(inherited)",
"@executable_path/../Frameworks",
);
MACOSX_DEPLOYMENT_TARGET = 12.3;
MARKETING_VERSION = 1.0;
PRODUCT_BUNDLE_IDENTIFIER = Z72PRUAWF6.com.maxgoedjen.SecretiveUpdater;
PRODUCT_NAME = Z72PRUAWF6.com.maxgoedjen.SecretiveUpdater;
SWIFT_EMIT_LOC_STRINGS = YES;
SWIFT_VERSION = 5.0;
};
name = Debug;
};
5081F6DE27B790DE0094B82D /* Test */ = {
isa = XCBuildConfiguration;
buildSettings = {
ASSETCATALOG_COMPILER_APPICON_NAME = AppIcon;
ASSETCATALOG_COMPILER_GLOBAL_ACCENT_COLOR_NAME = AccentColor;
CLANG_CXX_LANGUAGE_STANDARD = "gnu++17";
CODE_SIGN_ENTITLEMENTS = SecretiveUpdater/SecretiveUpdater.entitlements;
CODE_SIGN_STYLE = Automatic;
COMBINE_HIDPI_IMAGES = YES;
CURRENT_PROJECT_VERSION = 1;
DEVELOPMENT_TEAM = Z72PRUAWF6;
ENABLE_HARDENED_RUNTIME = YES;
GENERATE_INFOPLIST_FILE = YES;
INFOPLIST_FILE = SecretiveUpdater/Info.plist;
INFOPLIST_KEY_NSHumanReadableCopyright = "Copyright © 2022 Max Goedjen. All rights reserved.";
INFOPLIST_KEY_NSMainStoryboardFile = Main;
INFOPLIST_KEY_NSPrincipalClass = NSApplication;
LD_RUNPATH_SEARCH_PATHS = (
"$(inherited)",
"@executable_path/../Frameworks",
);
MACOSX_DEPLOYMENT_TARGET = 12.3;
MARKETING_VERSION = 1.0;
PRODUCT_BUNDLE_IDENTIFIER = Z72PRUAWF6.com.maxgoedjen.SecretiveUpdater;
PRODUCT_NAME = Z72PRUAWF6.com.maxgoedjen.SecretiveUpdater;
SWIFT_EMIT_LOC_STRINGS = YES;
SWIFT_VERSION = 5.0;
};
name = Test;
};
5081F6DF27B790DE0094B82D /* Release */ = {
isa = XCBuildConfiguration;
buildSettings = {
ASSETCATALOG_COMPILER_APPICON_NAME = AppIcon;
ASSETCATALOG_COMPILER_GLOBAL_ACCENT_COLOR_NAME = AccentColor;
CLANG_CXX_LANGUAGE_STANDARD = "gnu++17";
CODE_SIGN_ENTITLEMENTS = SecretiveUpdater/SecretiveUpdater.entitlements;
CODE_SIGN_STYLE = Automatic;
COMBINE_HIDPI_IMAGES = YES;
CURRENT_PROJECT_VERSION = 1;
DEVELOPMENT_TEAM = Z72PRUAWF6;
ENABLE_HARDENED_RUNTIME = YES;
GENERATE_INFOPLIST_FILE = YES;
INFOPLIST_FILE = SecretiveUpdater/Info.plist;
INFOPLIST_KEY_NSHumanReadableCopyright = "Copyright © 2022 Max Goedjen. All rights reserved.";
INFOPLIST_KEY_NSMainStoryboardFile = Main;
INFOPLIST_KEY_NSPrincipalClass = NSApplication;
LD_RUNPATH_SEARCH_PATHS = (
"$(inherited)",
"@executable_path/../Frameworks",
);
MACOSX_DEPLOYMENT_TARGET = 12.3;
MARKETING_VERSION = 1.0;
PRODUCT_BUNDLE_IDENTIFIER = Z72PRUAWF6.com.maxgoedjen.SecretiveUpdater;
PRODUCT_NAME = Z72PRUAWF6.com.maxgoedjen.SecretiveUpdater;
SWIFT_EMIT_LOC_STRINGS = YES;
SWIFT_VERSION = 5.0;
}; };
name = Release; name = Release;
}; };
@ -717,18 +1015,16 @@
GCC_WARN_UNINITIALIZED_AUTOS = YES_AGGRESSIVE; GCC_WARN_UNINITIALIZED_AUTOS = YES_AGGRESSIVE;
GCC_WARN_UNUSED_FUNCTION = YES; GCC_WARN_UNUSED_FUNCTION = YES;
GCC_WARN_UNUSED_VARIABLE = YES; GCC_WARN_UNUSED_VARIABLE = YES;
MACOSX_DEPLOYMENT_TARGET = 15.0; MACOSX_DEPLOYMENT_TARGET = 11.0;
MTL_ENABLE_DEBUG_INFO = INCLUDE_SOURCE; MTL_ENABLE_DEBUG_INFO = INCLUDE_SOURCE;
MTL_FAST_MATH = YES; MTL_FAST_MATH = YES;
ONLY_ACTIVE_ARCH = YES; ONLY_ACTIVE_ARCH = YES;
OTHER_SWIFT_FLAGS = ""; OTHER_SWIFT_FLAGS = "-Xfrontend -warn-concurrency -Xfrontend -enable-actor-data-race-checks";
SDKROOT = macosx; SDKROOT = macosx;
STRIP_INSTALLED_PRODUCT = NO; STRIP_INSTALLED_PRODUCT = NO;
STRIP_SWIFT_SYMBOLS = NO; STRIP_SWIFT_SYMBOLS = NO;
SWIFT_ACTIVE_COMPILATION_CONDITIONS = DEBUG; SWIFT_ACTIVE_COMPILATION_CONDITIONS = DEBUG;
SWIFT_EMIT_LOC_STRINGS = YES;
SWIFT_OPTIMIZATION_LEVEL = "-Onone"; SWIFT_OPTIMIZATION_LEVEL = "-Onone";
SWIFT_VERSION = 6.0;
}; };
name = Test; name = Test;
}; };
@ -737,6 +1033,7 @@
buildSettings = { buildSettings = {
ALWAYS_EMBED_SWIFT_STANDARD_LIBRARIES = YES; ALWAYS_EMBED_SWIFT_STANDARD_LIBRARIES = YES;
ASSETCATALOG_COMPILER_APPICON_NAME = AppIcon; ASSETCATALOG_COMPILER_APPICON_NAME = AppIcon;
CODE_SIGN_ENTITLEMENTS = Secretive/Secretive.entitlements;
CODE_SIGN_STYLE = Manual; CODE_SIGN_STYLE = Manual;
COMBINE_HIDPI_IMAGES = YES; COMBINE_HIDPI_IMAGES = YES;
CURRENT_PROJECT_VERSION = 1; CURRENT_PROJECT_VERSION = 1;
@ -751,6 +1048,29 @@
MARKETING_VERSION = 1; MARKETING_VERSION = 1;
PRODUCT_BUNDLE_IDENTIFIER = com.maxgoedjen.Secretive.Host; PRODUCT_BUNDLE_IDENTIFIER = com.maxgoedjen.Secretive.Host;
PRODUCT_NAME = "$(TARGET_NAME)"; PRODUCT_NAME = "$(TARGET_NAME)";
SWIFT_VERSION = 5.0;
};
name = Test;
};
508A5916241EF1A00069DC07 /* Test */ = {
isa = XCBuildConfiguration;
buildSettings = {
ALWAYS_EMBED_SWIFT_STANDARD_LIBRARIES = YES;
BUNDLE_LOADER = "$(TEST_HOST)";
CODE_SIGN_IDENTITY = "-";
CODE_SIGN_STYLE = Manual;
COMBINE_HIDPI_IMAGES = YES;
INFOPLIST_FILE = SecretiveTests/Info.plist;
LD_RUNPATH_SEARCH_PATHS = (
"$(inherited)",
"@executable_path/../Frameworks",
"@loader_path/../Frameworks",
);
PRODUCT_BUNDLE_IDENTIFIER = com.maxgoedjen.SecretiveTests;
PRODUCT_NAME = "$(TARGET_NAME)";
PROVISIONING_PROFILE_SPECIFIER = "";
SWIFT_VERSION = 5.0;
TEST_HOST = "$(BUILT_PRODUCTS_DIR)/Secretive.app/Contents/MacOS/Secretive";
}; };
name = Test; name = Test;
}; };
@ -771,6 +1091,7 @@
MARKETING_VERSION = 1; MARKETING_VERSION = 1;
PRODUCT_BUNDLE_IDENTIFIER = com.maxgoedjen.Secretive.SecretAgent; PRODUCT_BUNDLE_IDENTIFIER = com.maxgoedjen.Secretive.SecretAgent;
PRODUCT_NAME = "$(TARGET_NAME)"; PRODUCT_NAME = "$(TARGET_NAME)";
SWIFT_VERSION = 5.0;
}; };
name = Test; name = Test;
}; };
@ -793,6 +1114,7 @@
MARKETING_VERSION = 1; MARKETING_VERSION = 1;
PRODUCT_BUNDLE_IDENTIFIER = com.maxgoedjen.Secretive.SecretAgent; PRODUCT_BUNDLE_IDENTIFIER = com.maxgoedjen.Secretive.SecretAgent;
PRODUCT_NAME = "$(TARGET_NAME)"; PRODUCT_NAME = "$(TARGET_NAME)";
SWIFT_VERSION = 5.0;
}; };
name = Debug; name = Debug;
}; };
@ -817,6 +1139,7 @@
PRODUCT_BUNDLE_IDENTIFIER = com.maxgoedjen.Secretive.SecretAgent; PRODUCT_BUNDLE_IDENTIFIER = com.maxgoedjen.Secretive.SecretAgent;
PRODUCT_NAME = "$(TARGET_NAME)"; PRODUCT_NAME = "$(TARGET_NAME)";
PROVISIONING_PROFILE_SPECIFIER = "Secretive - Secret Agent"; PROVISIONING_PROFILE_SPECIFIER = "Secretive - Secret Agent";
SWIFT_VERSION = 5.0;
}; };
name = Release; name = Release;
}; };
@ -843,6 +1166,26 @@
defaultConfigurationIsVisible = 0; defaultConfigurationIsVisible = 0;
defaultConfigurationName = Release; defaultConfigurationName = Release;
}; };
50617DA023FCE48E0099B055 /* Build configuration list for PBXNativeTarget "SecretiveTests" */ = {
isa = XCConfigurationList;
buildConfigurations = (
50617DA123FCE48E0099B055 /* Debug */,
508A5916241EF1A00069DC07 /* Test */,
50617DA223FCE48E0099B055 /* Release */,
);
defaultConfigurationIsVisible = 0;
defaultConfigurationName = Release;
};
5081F6DC27B790DE0094B82D /* Build configuration list for PBXNativeTarget "SecretiveUpdater" */ = {
isa = XCConfigurationList;
buildConfigurations = (
5081F6DD27B790DE0094B82D /* Debug */,
5081F6DE27B790DE0094B82D /* Test */,
5081F6DF27B790DE0094B82D /* Release */,
);
defaultConfigurationIsVisible = 0;
defaultConfigurationName = Release;
};
50A3B79A24026B7600D209EA /* Build configuration list for PBXNativeTarget "SecretAgent" */ = { 50A3B79A24026B7600D209EA /* Build configuration list for PBXNativeTarget "SecretAgent" */ = {
isa = XCConfigurationList; isa = XCConfigurationList;
buildConfigurations = ( buildConfigurations = (
@ -892,6 +1235,10 @@
isa = XCSwiftPackageProductDependency; isa = XCSwiftPackageProductDependency;
productName = Brief; productName = Brief;
}; };
5081F6E227B791620094B82D /* Brief */ = {
isa = XCSwiftPackageProductDependency;
productName = Brief;
};
/* End XCSwiftPackageProductDependency section */ /* End XCSwiftPackageProductDependency section */
}; };
rootObject = 50617D7723FCE48D0099B055 /* Project object */; rootObject = 50617D7723FCE48D0099B055 /* Project object */;

View File

@ -75,7 +75,6 @@
ignoresPersistentStateOnLaunch = "NO" ignoresPersistentStateOnLaunch = "NO"
debugDocumentVersioning = "YES" debugDocumentVersioning = "YES"
debugServiceExtension = "internal" debugServiceExtension = "internal"
enableGPUValidationMode = "1"
allowLocationSimulation = "YES"> allowLocationSimulation = "YES">
<BuildableProductRunnable <BuildableProductRunnable
runnableDebuggingMode = "0"> runnableDebuggingMode = "0">

View File

@ -0,0 +1,78 @@
<?xml version="1.0" encoding="UTF-8"?>
<Scheme
LastUpgradeVersion = "1330"
version = "1.3">
<BuildAction
parallelizeBuildables = "YES"
buildImplicitDependencies = "YES">
<BuildActionEntries>
<BuildActionEntry
buildForTesting = "YES"
buildForRunning = "YES"
buildForProfiling = "YES"
buildForArchiving = "YES"
buildForAnalyzing = "YES">
<BuildableReference
BuildableIdentifier = "primary"
BlueprintIdentifier = "5081F6CF27B790DD0094B82D"
BuildableName = "Z72PRUAWF6.com.maxgoedjen.SecretiveUpdater.app"
BlueprintName = "SecretiveUpdater"
ReferencedContainer = "container:Secretive.xcodeproj">
</BuildableReference>
</BuildActionEntry>
</BuildActionEntries>
</BuildAction>
<TestAction
buildConfiguration = "Debug"
selectedDebuggerIdentifier = "Xcode.DebuggerFoundation.Debugger.LLDB"
selectedLauncherIdentifier = "Xcode.DebuggerFoundation.Launcher.LLDB"
shouldUseLaunchSchemeArgsEnv = "YES">
<Testables>
</Testables>
</TestAction>
<LaunchAction
buildConfiguration = "Debug"
selectedDebuggerIdentifier = "Xcode.DebuggerFoundation.Debugger.LLDB"
selectedLauncherIdentifier = "Xcode.DebuggerFoundation.Launcher.LLDB"
launchStyle = "0"
useCustomWorkingDirectory = "NO"
ignoresPersistentStateOnLaunch = "NO"
debugDocumentVersioning = "YES"
debugServiceExtension = "internal"
allowLocationSimulation = "YES">
<BuildableProductRunnable
runnableDebuggingMode = "0">
<BuildableReference
BuildableIdentifier = "primary"
BlueprintIdentifier = "5081F6CF27B790DD0094B82D"
BuildableName = "Z72PRUAWF6.com.maxgoedjen.SecretiveUpdater.app"
BlueprintName = "SecretiveUpdater"
ReferencedContainer = "container:Secretive.xcodeproj">
</BuildableReference>
</BuildableProductRunnable>
</LaunchAction>
<ProfileAction
buildConfiguration = "Release"
shouldUseLaunchSchemeArgsEnv = "YES"
savedToolIdentifier = ""
useCustomWorkingDirectory = "NO"
debugDocumentVersioning = "YES">
<BuildableProductRunnable
runnableDebuggingMode = "0">
<BuildableReference
BuildableIdentifier = "primary"
BlueprintIdentifier = "5081F6CF27B790DD0094B82D"
BuildableName = "Z72PRUAWF6.com.maxgoedjen.SecretiveUpdater.app"
BlueprintName = "SecretiveUpdater"
ReferencedContainer = "container:Secretive.xcodeproj">
</BuildableReference>
</BuildableProductRunnable>
</ProfileAction>
<AnalyzeAction
buildConfiguration = "Debug">
</AnalyzeAction>
<ArchiveAction
buildConfiguration = "Release"
revealArchiveInOrganizer = "YES">
</ArchiveAction>
</Scheme>

View File

@ -5,17 +5,6 @@ import SecureEnclaveSecretKit
import SmartCardSecretKit import SmartCardSecretKit
import Brief import Brief
extension EnvironmentValues {
@Entry var secretStoreList: SecretStoreList = {
let list = SecretStoreList()
list.add(store: SecureEnclave.Store())
list.add(store: SmartCard.Store())
return list
}()
@Entry var agentStatusChecker: any AgentStatusCheckerProtocol = AgentStatusChecker()
@Entry var updater: any UpdaterProtocol = Updater(checkOnLaunch: false)
}
@main @main
struct Secretive: App { struct Secretive: App {
@ -27,6 +16,7 @@ struct Secretive: App {
}() }()
private let agentStatusChecker = AgentStatusChecker() private let agentStatusChecker = AgentStatusChecker()
private let justUpdatedChecker = JustUpdatedChecker() private let justUpdatedChecker = JustUpdatedChecker()
private let updaterController = UpdaterCommunicationController()
@AppStorage("defaultsHasRunSetup") var hasRunSetup = false @AppStorage("defaultsHasRunSetup") var hasRunSetup = false
@State private var showingSetup = false @State private var showingSetup = false
@ -34,11 +24,12 @@ struct Secretive: App {
@SceneBuilder var body: some Scene { @SceneBuilder var body: some Scene {
WindowGroup { WindowGroup {
ContentView(showingCreation: $showingCreation, runningSetup: $showingSetup, hasRunSetup: $hasRunSetup) ContentView<UpdateChecker, AgentStatusChecker>(showingCreation: $showingCreation, runningSetup: $showingSetup, hasRunSetup: $hasRunSetup)
.environment(storeList) .environmentObject(storeList)
.environment(Updater(checkOnLaunch: hasRunSetup)) .environmentObject(UpdateChecker(checkOnLaunch: hasRunSetup))
.environment(agentStatusChecker) .environmentObject(agentStatusChecker)
.onAppear { .onAppear {
updaterController.installUpdate(url: URL(string: "https://github.com/maxgoedjen/secretive/releases/download/v2.1.1/Secretive.zip")!)
if !hasRunSetup { if !hasRunSetup {
showingSetup = true showingSetup = true
} }
@ -56,18 +47,18 @@ struct Secretive: App {
} }
.commands { .commands {
CommandGroup(after: CommandGroupPlacement.newItem) { CommandGroup(after: CommandGroupPlacement.newItem) {
Button("app_menu_new_secret_button") { Button("New Secret") {
showingCreation = true showingCreation = true
} }
.keyboardShortcut(KeyboardShortcut(KeyEquivalent("N"), modifiers: [.command, .shift])) .keyboardShortcut(KeyboardShortcut(KeyEquivalent("N"), modifiers: [.command, .shift]))
} }
CommandGroup(replacing: .help) { CommandGroup(replacing: .help) {
Button("app_menu_help_button") { Button("Help") {
NSWorkspace.shared.open(Constants.helpURL) NSWorkspace.shared.open(Constants.helpURL)
} }
} }
CommandGroup(after: .help) { CommandGroup(after: .help) {
Button("app_menu_setup_button") { Button("Setup Secretive") {
showingSetup = true showingSetup = true
} }
} }
@ -81,12 +72,13 @@ extension Secretive {
private func reinstallAgent() { private func reinstallAgent() {
justUpdatedChecker.check() justUpdatedChecker.check()
Task { LaunchAgentController().install {
await LaunchAgentController().install() // Wait a second for launchd to kick in (next runloop isn't enough).
try? await Task.sleep(for: .seconds(1)) DispatchQueue.main.asyncAfter(deadline: .now() + 1) {
agentStatusChecker.check() agentStatusChecker.check()
if !agentStatusChecker.running { if !agentStatusChecker.running {
forceLaunchAgent() forceLaunchAgent()
}
} }
} }
} }
@ -94,8 +86,7 @@ extension Secretive {
private func forceLaunchAgent() { private func forceLaunchAgent() {
// We've run setup, we didn't just update, launchd is just not doing it's thing. // We've run setup, we didn't just update, launchd is just not doing it's thing.
// Force a launch directly. // Force a launch directly.
Task { LaunchAgentController().forceLaunch { _ in
_ = await LaunchAgentController().forceLaunch()
agentStatusChecker.check() agentStatusChecker.check()
} }
} }

View File

@ -2,16 +2,15 @@ import Foundation
import Combine import Combine
import AppKit import AppKit
import SecretKit import SecretKit
import Observation
protocol AgentStatusCheckerProtocol: Observable { protocol AgentStatusCheckerProtocol: ObservableObject {
var running: Bool { get } var running: Bool { get }
var developmentBuild: Bool { get } var developmentBuild: Bool { get }
} }
@Observable class AgentStatusChecker: AgentStatusCheckerProtocol { class AgentStatusChecker: ObservableObject, AgentStatusCheckerProtocol {
var running: Bool = false @Published var running: Bool = false
init() { init() {
check() check()

View File

@ -6,47 +6,38 @@ import SecretKit
struct LaunchAgentController { struct LaunchAgentController {
private let logger = Logger(subsystem: "com.maxgoedjen.secretive", category: "LaunchAgentController") func install(completion: (() -> Void)? = nil) {
Logger().debug("Installing agent")
func install() async {
logger.debug("Installing agent")
_ = setEnabled(false) _ = setEnabled(false)
// This is definitely a bit of a "seems to work better" thing but: // This is definitely a bit of a "seems to work better" thing but:
// Seems to more reliably hit if these are on separate runloops, otherwise it seems like it sometimes doesn't kill old // Seems to more reliably hit if these are on separate runloops, otherwise it seems like it sometimes doesn't kill old
// and start new? // and start new?
try? await Task.sleep(for: .seconds(1)) DispatchQueue.main.asyncAfter(deadline: .now() + 0.1) {
await MainActor.run {
_ = setEnabled(true) _ = setEnabled(true)
completion?()
} }
} }
func forceLaunch() async -> Bool { func forceLaunch(completion: ((Bool) -> Void)?) {
logger.debug("Agent is not running, attempting to force launch") Logger().debug("Agent is not running, attempting to force launch")
let url = Bundle.main.bundleURL.appendingPathComponent("Contents/Library/LoginItems/SecretAgent.app") let url = Bundle.main.bundleURL.appendingPathComponent("Contents/Library/LoginItems/SecretAgent.app")
let config = NSWorkspace.OpenConfiguration() let config = NSWorkspace.OpenConfiguration()
config.activates = false config.activates = false
do { NSWorkspace.shared.openApplication(at: url, configuration: config) { app, error in
try await NSWorkspace.shared.openApplication(at: url, configuration: config) DispatchQueue.main.async {
logger.debug("Agent force launched") completion?(error == nil)
return true }
} catch { if let error = error {
logger.error("Error force launching \(error.localizedDescription)") Logger().error("Error force launching \(error.localizedDescription)")
return false } else {
Logger().debug("Agent force launched")
}
} }
} }
private func setEnabled(_ enabled: Bool) -> Bool { private func setEnabled(_ enabled: Bool) -> Bool {
let service = SMAppService.loginItem(identifier: Bundle.main.agentBundleID) SMLoginItemSetEnabled(Bundle.main.agentBundleID as CFString, enabled)
do {
if enabled {
try service.register()
} else {
try service.unregister()
}
return true
} catch {
return false
}
} }
} }

View File

@ -0,0 +1,41 @@
import Foundation
import Combine
import AppKit
import OSLog
import SecretKit
//import SecretiveUpdater
import ServiceManagement
class UpdaterCommunicationController: ObservableObject {
private(set) var updater: UpdaterProtocol? = nil
private var connection: NSXPCConnection? = nil
private var running = false
init() {
}
func installUpdate(url: URL) {
guard !running else { return }
_ = SMLoginItemSetEnabled(Bundle.main.updaterBundleID as CFString, false)
SMLoginItemSetEnabled(Bundle.main.updaterBundleID as CFString, true)
connection = NSXPCConnection(machServiceName: Bundle.main.updaterBundleID)
connection?.remoteObjectInterface = NSXPCInterface(with: UpdaterProtocol.self)
connection?.invalidationHandler = {
Logger().warning("XPC connection invalidated")
}
connection?.resume()
updater = connection?.remoteObjectProxyWithErrorHandler({ error in
Logger().error("\(String(describing: error))")
}) as? UpdaterProtocol
running = true
let existingURL = Bundle.main.bundleURL
Task {
let result = try await updater?.installUpdate(url: url, to: existingURL)
print(result)
}
}
}

View File

@ -4,4 +4,5 @@ import Foundation
extension Bundle { extension Bundle {
public var agentBundleID: String {(self.bundleIdentifier?.replacingOccurrences(of: "Host", with: "SecretAgent"))!} public var agentBundleID: String {(self.bundleIdentifier?.replacingOccurrences(of: "Host", with: "SecretAgent"))!}
public var hostBundleID: String {(self.bundleIdentifier?.replacingOccurrences(of: "SecretAgent", with: "Host"))!} public var hostBundleID: String {(self.bundleIdentifier?.replacingOccurrences(of: "SecretAgent", with: "Host"))!}
public var updaterBundleID: String { "Z72PRUAWF6.com.maxgoedjen.SecretiveUpdater" }
} }

File diff suppressed because it is too large Load Diff

View File

@ -11,76 +11,64 @@ extension Preview {
let name: String let name: String
let algorithm = Algorithm.ellipticCurve let algorithm = Algorithm.ellipticCurve
let keySize = 256 let keySize = 256
let requiresAuthentication: Bool = false
let publicKey = UUID().uuidString.data(using: .utf8)! let publicKey = UUID().uuidString.data(using: .utf8)!
} }
} }
//extension Preview { extension Preview {
//
// class Store: SecretStore, ObservableObject { class Store: SecretStore, ObservableObject {
//
// let isAvailable = true let isAvailable = true
// let id = UUID() let id = UUID()
// var name: String { "Preview Store" } var name: String { "Preview Store" }
// @Published var secrets: [Secret] = [] @Published var secrets: [Secret] = []
//
// init(secrets: [Secret]) { init(secrets: [Secret]) {
// self.secrets.append(contentsOf: secrets) self.secrets.append(contentsOf: secrets)
// } }
//
// init(numberOfRandomSecrets: Int = 5) { init(numberOfRandomSecrets: Int = 5) {
// let new = (0..<numberOfRandomSecrets).map { Secret(name: String(describing: $0)) } let new = (0..<numberOfRandomSecrets).map { Secret(name: String(describing: $0)) }
// self.secrets.append(contentsOf: new) self.secrets.append(contentsOf: new)
// } }
//
// func sign(data: Data, with secret: Preview.Secret, for provenance: SigningRequestProvenance) throws -> Data { func sign(data: Data, with secret: Preview.Secret, for provenance: SigningRequestProvenance) throws -> SignedData {
// return data return SignedData(data: data, requiredAuthentication: false)
// } }
//
// func verify(signature data: Data, for signature: Data, with secret: Preview.Secret) throws -> Bool { func persistAuthentication(secret: Preview.Secret, forDuration duration: TimeInterval) throws {
// true }
// }
// }
// func existingPersistedAuthenticationContext(secret: Preview.Secret) -> PersistedAuthenticationContext? {
// nil class StoreModifiable: Store, SecretStoreModifiable {
// } override var name: String { "Modifiable Preview Store" }
//
// func persistAuthentication(secret: Preview.Secret, forDuration duration: TimeInterval) throws { func create(name: String, requiresAuthentication: Bool) throws {
// } }
//
// func reloadSecrets() { func delete(secret: Preview.Secret) throws {
// } }
//
// } func update(secret: Preview.Secret, name: String) throws {
// }
// class StoreModifiable: Store, SecretStoreModifiable { }
// override var name: String { "Modifiable Preview Store" } }
//
// func create(name: String, requiresAuthentication: Bool) throws { extension Preview {
// }
// static func storeList(stores: [Store] = [], modifiableStores: [StoreModifiable] = []) -> SecretStoreList {
// func delete(secret: Preview.Secret) throws { let list = SecretStoreList()
// } for store in stores {
// list.add(store: store)
// func update(secret: Preview.Secret, name: String) throws { }
// } for storeModifiable in modifiableStores {
// } list.add(store: storeModifiable)
//} }
// return list
//extension Preview { }
//
// static func storeList(stores: [Store] = [], modifiableStores: [StoreModifiable] = []) -> SecretStoreList { }
// let list = SecretStoreList()
// for store in stores {
// list.add(store: store)
// }
// for storeModifiable in modifiableStores {
// list.add(store: storeModifiable)
// }
// return list
// }
//
//}

View File

@ -1,32 +1,20 @@
import Foundation import Foundation
import Synchronization import Combine
import Observation
import Brief import Brief
@Observable class PreviewUpdater: UpdaterProtocol { class PreviewUpdater: UpdateCheckerProtocol {
var update: Release? {
_update.withLock { $0 }
}
let _update: Mutex<Release?> = .init(nil)
let update: Release?
let testBuild = false let testBuild = false
init(update: Update = .none) { init(update: Update = .none) {
switch update { switch update {
case .none: case .none:
_update.withLock { self.update = nil
$0 = nil
}
case .advisory: case .advisory:
_update.withLock { self.update = Release(name: "10.10.10", prerelease: false, html_url: URL(string: "https://example.com")!, body: "Some regular update")
$0 = Release(name: "10.10.10", prerelease: false, html_url: URL(string: "https://example.com")!, body: "Some regular update")
}
case .critical: case .critical:
_update.withLock { self.update = Release(name: "10.10.10", prerelease: false, html_url: URL(string: "https://example.com")!, body: "Critical Security Update")
$0 = Release(name: "10.10.10", prerelease: false, html_url: URL(string: "https://example.com")!, body: "Critical Security Update")
}
} }
} }

View File

@ -4,6 +4,10 @@
<dict> <dict>
<key>com.apple.security.app-sandbox</key> <key>com.apple.security.app-sandbox</key>
<true/> <true/>
<key>com.apple.security.application-groups</key>
<array>
<string>$(TeamIdentifierPrefix)com.maxgoedjen.Secretive</string>
</array>
<key>com.apple.security.files.user-selected.read-write</key> <key>com.apple.security.files.user-selected.read-write</key>
<true/> <true/>
<key>com.apple.security.network.client</key> <key>com.apple.security.network.client</key>

View File

@ -4,18 +4,15 @@ import SecureEnclaveSecretKit
import SmartCardSecretKit import SmartCardSecretKit
import Brief import Brief
struct ContentView: View { struct ContentView<UpdaterType: UpdateCheckerProtocol, AgentStatusCheckerType: AgentStatusCheckerProtocol>: View {
@Binding var showingCreation: Bool @Binding var showingCreation: Bool
@Binding var runningSetup: Bool @Binding var runningSetup: Bool
@Binding var hasRunSetup: Bool @Binding var hasRunSetup: Bool
@State var showingAgentInfo = false
@State var activeSecret: AnySecret.ID?
@Environment(\.colorScheme) var colorScheme
@Environment(\.secretStoreList) private var storeList: SecretStoreList @EnvironmentObject private var storeList: SecretStoreList
@Environment(\.updater) private var updater: any UpdaterProtocol @EnvironmentObject private var updater: UpdaterType
@Environment(\.agentStatusChecker) private var agentStatusChecker: any AgentStatusCheckerProtocol @EnvironmentObject private var agentStatusChecker: AgentStatusCheckerType
@State private var selectedUpdate: Release? @State private var selectedUpdate: Release?
@State private var showingAppPathNotice = false @State private var showingAppPathNotice = false
@ -23,17 +20,17 @@ struct ContentView: View {
var body: some View { var body: some View {
VStack { VStack {
if storeList.anyAvailable { if storeList.anyAvailable {
StoreListView(activeSecret: $activeSecret) StoreListView(showingCreation: $showingCreation)
} else { } else {
NoStoresView() NoStoresView()
} }
} }
.frame(minWidth: 640, minHeight: 320) .frame(minWidth: 640, minHeight: 320)
.toolbar { .toolbar {
toolbarItem(updateNoticeView, id: "update") updateNotice
toolbarItem(runningOrRunSetupView, id: "setup") setupNotice
toolbarItem(appPathNoticeView, id: "appPath") appPathNotice
toolbarItem(newItemView, id: "new") newItem
} }
.sheet(isPresented: $runningSetup) { .sheet(isPresented: $runningSetup) {
SetupView(visible: $runningSetup, setupComplete: $hasRunSetup) SetupView(visible: $runningSetup, setupComplete: $hasRunSetup)
@ -44,190 +41,160 @@ struct ContentView: View {
extension ContentView { extension ContentView {
var updateNotice: ToolbarItem<Void, AnyView> {
func toolbarItem(_ view: some View, id: String) -> ToolbarItem<String, some View> { guard let update = updater.update else {
ToolbarItem(id: id) { view } return ToolbarItem { AnyView(EmptyView()) }
}
var needsSetup: Bool {
(runningSetup || !hasRunSetup || !agentStatusChecker.running) && !agentStatusChecker.developmentBuild
}
/// Item either showing a "everything's good, here's more info" or "something's wrong, re-run setup" message
/// These two are mutually exclusive
@ViewBuilder
var runningOrRunSetupView: some View {
if needsSetup {
setupNoticeView
} else {
runningNoticeView
} }
} let color: Color
let text: String
var updateNoticeContent: (LocalizedStringKey, Color)? {
guard let update = updater.update else { return nil }
if update.critical { if update.critical {
return ("update_critical_notice_title", .red) text = "Critical Security Update Required"
color = .red
} else { } else {
if updater.testBuild { if updater.testBuild {
return ("update_test_notice_title", .blue) text = "Test Build"
color = .blue
} else { } else {
return ("update_normal_notice_title", .orange) text = "Update Available"
color = .orange
} }
} }
return ToolbarItem {
AnyView(
Button(action: {
selectedUpdate = update
}, label: {
Text(text)
.font(.headline)
.foregroundColor(.white)
})
.background(color)
.cornerRadius(5)
.popover(item: $selectedUpdate, attachmentAnchor: .point(.bottom), arrowEdge: .bottom) { update in
UpdateDetailView(update: update)
}
)
}
} }
@ViewBuilder var newItem: ToolbarItem<Void, AnyView> {
var updateNoticeView: some View { guard storeList.modifiableStore?.isAvailable ?? false else {
if let update = updater.update, let (text, color) = updateNoticeContent { return ToolbarItem { AnyView(EmptyView()) }
Button(action: { }
selectedUpdate = update return ToolbarItem {
}, label: { AnyView(
Text(text) Button(action: {
showingCreation = true
}, label: {
Image(systemName: "plus")
})
.popover(isPresented: $showingCreation, attachmentAnchor: .point(.bottom), arrowEdge: .bottom) {
if let modifiable = storeList.modifiableStore {
CreateSecretView(store: modifiable, showing: $showingCreation)
}
}
)
}
}
var setupNotice: ToolbarItem<Void, AnyView> {
return ToolbarItem {
AnyView(
Group {
if (runningSetup || !hasRunSetup || !agentStatusChecker.running) && !agentStatusChecker.developmentBuild {
Button(action: {
runningSetup = true
}, label: {
Group {
if hasRunSetup && !agentStatusChecker.running {
Text("Secret Agent Is Not Running")
} else {
Text("Setup Secretive")
}
}
.font(.headline)
.foregroundColor(.white)
})
.background(Color.orange)
.cornerRadius(5)
} else {
EmptyView()
}
}
)
}
}
var appPathNotice: ToolbarItem<Void, AnyView> {
let controller = ApplicationDirectoryController()
guard !controller.isInApplicationsDirectory else {
return ToolbarItem { AnyView(EmptyView()) }
}
return ToolbarItem {
AnyView(
Button(action: {
showingAppPathNotice = true
}, label: {
Group {
Text("Secretive Is Not in Applications Folder")
}
.font(.headline) .font(.headline)
.foregroundColor(.white) .foregroundColor(.white)
}) })
.buttonStyle(ToolbarButtonStyle(color: color)) .background(Color.orange)
.popover(item: $selectedUpdate, attachmentAnchor: attachmentAnchor, arrowEdge: .bottom) { update in .cornerRadius(5)
UpdateDetailView(update: update) .popover(isPresented: $showingAppPathNotice, attachmentAnchor: .point(.bottom), arrowEdge: .bottom) {
} VStack {
} Image(systemName: "exclamationmark.triangle")
} .resizable()
.aspectRatio(contentMode: .fit)
@ViewBuilder .frame(width: 64)
var newItemView: some View { Text("Secretive needs to be in your Applications folder to work properly. Please move it and relaunch.")
if storeList.modifiableStore?.isAvailable ?? false { .frame(maxWidth: 300)
Button(action: { }
showingCreation = true .padding()
}, label: {
Image(systemName: "plus")
})
.sheet(isPresented: $showingCreation) {
if let modifiable = storeList.modifiableStore {
CreateSecretView(store: modifiable, showing: $showingCreation)
.onDisappear {
guard let newest = modifiable.secrets.last?.id else { return }
activeSecret = newest
}
} }
} )
} }
} }
@ViewBuilder
var setupNoticeView: some View {
Button(action: {
runningSetup = true
}, label: {
Group {
if hasRunSetup && !agentStatusChecker.running {
Text("agent_not_running_notice_title")
} else {
Text("agent_setup_notice_title")
}
}
.font(.headline)
.foregroundColor(.white)
})
.buttonStyle(ToolbarButtonStyle(color: .orange))
}
@ViewBuilder
var runningNoticeView: some View {
Button(action: {
showingAgentInfo = true
}, label: {
HStack {
Text("agent_running_notice_title")
.font(.headline)
.foregroundColor(colorScheme == .light ? Color(white: 0.3) : .white)
Circle()
.frame(width: 10, height: 10)
.foregroundColor(Color.green)
}
})
.buttonStyle(ToolbarButtonStyle(lightColor: .black.opacity(0.05), darkColor: .white.opacity(0.05)))
.popover(isPresented: $showingAgentInfo, attachmentAnchor: attachmentAnchor, arrowEdge: .bottom) {
VStack {
Text("agent_running_notice_detail_title")
.font(.title)
.padding(5)
Text("agent_running_notice_detail_description")
.frame(width: 300)
}
.padding()
}
}
@ViewBuilder
var appPathNoticeView: some View {
if !ApplicationDirectoryController().isInApplicationsDirectory {
Button(action: {
showingAppPathNotice = true
}, label: {
Group {
Text("app_not_in_applications_notice_title")
}
.font(.headline)
.foregroundColor(.white)
})
.buttonStyle(ToolbarButtonStyle(color: .orange))
.popover(isPresented: $showingAppPathNotice, attachmentAnchor: attachmentAnchor, arrowEdge: .bottom) {
VStack {
Image(systemName: "exclamationmark.triangle")
.resizable()
.aspectRatio(contentMode: .fit)
.frame(width: 64)
Text("app_not_in_applications_notice_detail_description")
.frame(maxWidth: 300)
}
.padding()
}
}
}
var attachmentAnchor: PopoverAttachmentAnchor {
// Ideally .point(.bottom), but broken on Sonoma (FB12726503)
.rect(.bounds)
}
} }
//#if DEBUG #if DEBUG
//
//struct ContentView_Previews: PreviewProvider {
//
// private static let storeList: SecretStoreList = {
// let list = SecretStoreList()
// list.add(store: SecureEnclave.Store())
// list.add(store: SmartCard.Store())
// return list
// }()
// private static let agentStatusChecker = AgentStatusChecker()
// private static let justUpdatedChecker = JustUpdatedChecker()
//
// @State var hasRunSetup = false
// @State private var showingSetup = false
// @State private var showingCreation = false
//
// static var previews: some View {
// Group {
// // Empty on modifiable and nonmodifiable
// ContentView<PreviewUpdater, AgentStatusChecker>(showingCreation: .constant(false), runningSetup: .constant(false), hasRunSetup: .constant(true))
// .environmentObject(Preview.storeList(stores: [Preview.Store(numberOfRandomSecrets: 0)], modifiableStores: [Preview.StoreModifiable(numberOfRandomSecrets: 0)]))
// .environmentObject(PreviewUpdater())
// .environmentObject(agentStatusChecker)
//
// // 5 items on modifiable and nonmodifiable
// ContentView<PreviewUpdater, AgentStatusChecker>(showingCreation: .constant(false), runningSetup: .constant(false), hasRunSetup: .constant(true))
// .environmentObject(Preview.storeList(stores: [Preview.Store()], modifiableStores: [Preview.StoreModifiable()]))
// .environmentObject(PreviewUpdater())
// .environmentObject(agentStatusChecker)
// }
// .environmentObject(agentStatusChecker)
//
// }
//}
//
//#endif
struct ContentView_Previews: PreviewProvider {
private static let storeList: SecretStoreList = {
let list = SecretStoreList()
list.add(store: SecureEnclave.Store())
list.add(store: SmartCard.Store())
return list
}()
private static let agentStatusChecker = AgentStatusChecker()
private static let justUpdatedChecker = JustUpdatedChecker()
@State var hasRunSetup = false
@State private var showingSetup = false
@State private var showingCreation = false
static var previews: some View {
Group {
// Empty on modifiable and nonmodifiable
ContentView<PreviewUpdater, AgentStatusChecker>(showingCreation: .constant(false), runningSetup: .constant(false), hasRunSetup: .constant(true))
.environmentObject(Preview.storeList(stores: [Preview.Store(numberOfRandomSecrets: 0)], modifiableStores: [Preview.StoreModifiable(numberOfRandomSecrets: 0)]))
.environmentObject(PreviewUpdater())
.environmentObject(agentStatusChecker)
// 5 items on modifiable and nonmodifiable
ContentView<PreviewUpdater, AgentStatusChecker>(showingCreation: .constant(false), runningSetup: .constant(false), hasRunSetup: .constant(true))
.environmentObject(Preview.storeList(stores: [Preview.Store()], modifiableStores: [Preview.StoreModifiable()]))
.environmentObject(PreviewUpdater())
.environmentObject(agentStatusChecker)
}
.environmentObject(agentStatusChecker)
}
}
#endif

View File

@ -3,12 +3,11 @@ import UniformTypeIdentifiers
struct CopyableView: View { struct CopyableView: View {
var title: LocalizedStringKey var title: String
var image: Image var image: Image
var text: String var text: String
@State private var interactionState: InteractionState = .normal @State private var interactionState: InteractionState = .normal
@Environment(\.colorScheme) private var colorScheme
var body: some View { var body: some View {
VStack(alignment: .leading) { VStack(alignment: .leading) {
@ -66,44 +65,50 @@ struct CopyableView: View {
) )
} }
var hoverText: LocalizedStringKey { var hoverText: String {
switch interactionState { switch interactionState {
case .hovering: case .hovering:
return "copyable_click_to_copy_button" return "Click to Copy"
case .clicking: case .clicking:
return "copyable_copied" return "Copied"
case .normal: case .normal:
fatalError() fatalError()
} }
} }
var backgroundColor: Color { var backgroundColor: Color {
let color: NSColor
switch interactionState { switch interactionState {
case .normal: case .normal:
return colorScheme == .dark ? Color(white: 0.2) : Color(white: 0.885) color = .windowBackgroundColor
case .hovering: case .hovering:
return colorScheme == .dark ? Color(white: 0.275) : Color(white: 0.82) color = .unemphasizedSelectedContentBackgroundColor
case .clicking: case .clicking:
return .accentColor color = .selectedContentBackgroundColor
} }
return Color(color)
} }
var primaryTextColor: Color { var primaryTextColor: Color {
let color: NSColor
switch interactionState { switch interactionState {
case .normal, .hovering: case .normal, .hovering:
return Color(.textColor) color = .textColor
case .clicking: case .clicking:
return .white color = .white
} }
return Color(color)
} }
var secondaryTextColor: Color { var secondaryTextColor: Color {
let color: NSColor
switch interactionState { switch interactionState {
case .normal, .hovering: case .normal, .hovering:
return Color(.secondaryLabelColor) color = .secondaryLabelColor
case .clicking: case .clicking:
return .white color = .white
} }
return Color(color)
} }
func copy() { func copy() {
@ -122,10 +127,8 @@ struct CopyableView: View {
struct CopyableView_Previews: PreviewProvider { struct CopyableView_Previews: PreviewProvider {
static var previews: some View { static var previews: some View {
Group { Group {
CopyableView(title: "secret_detail_sha256_fingerprint_label", image: Image(systemName: "figure.wave"), text: "Hello world.") CopyableView(title: "Title", image: Image(systemName: "figure.wave"), text: "Hello world.")
.padding() CopyableView(title: "Title", image: Image(systemName: "figure.wave"), text: "Long text. Long text. Long text. Long text. Long text. Long text. Long text. Long text. Long text. Long text. Long text. Long text. Long text. Long text. Long text. Long text. Long text. Long text. Long text. Long text. Long text. Long text. Long text. Long text. Long text. Long text. Long text. Long text. Long text. ")
CopyableView(title: "secret_detail_sha256_fingerprint_label", image: Image(systemName: "figure.wave"), text: "Long text. Long text. Long text. Long text. Long text. Long text. Long text. Long text. Long text. Long text. Long text. Long text. Long text. Long text. Long text. Long text. Long text. Long text. Long text. Long text. Long text. Long text. Long text. Long text. Long text. Long text. Long text. Long text. Long text. ")
.padding()
} }
} }
} }

View File

@ -3,7 +3,7 @@ import SecretKit
struct CreateSecretView<StoreType: SecretStoreModifiable>: View { struct CreateSecretView<StoreType: SecretStoreModifiable>: View {
@State var store: StoreType @ObservedObject var store: StoreType
@Binding var showing: Bool @Binding var showing: Bool
@State private var name = "" @State private var name = ""
@ -12,32 +12,38 @@ struct CreateSecretView<StoreType: SecretStoreModifiable>: View {
var body: some View { var body: some View {
VStack { VStack {
HStack { HStack {
Image(nsImage: NSApplication.shared.applicationIconImage)
.resizable()
.frame(width: 64, height: 64)
.padding()
VStack { VStack {
HStack { HStack {
Text("create_secret_title") Text("Create a New Secret").bold()
.font(.largeTitle)
Spacer() Spacer()
} }
HStack { HStack {
Text("create_secret_name_label") Text("Name:")
TextField("create_secret_name_placeholder", text: $name) TextField("Shhhhh", text: $name).focusable()
.focusable() }
HStack {
VStack(spacing: 20) {
Picker("", selection: $requiresAuthentication) {
Text("Requires Authentication (Biometrics or Password) before each use").tag(true)
Text("Authentication not required when Mac is unlocked").tag(false)
}
.pickerStyle(RadioGroupPickerStyle())
}
Spacer()
} }
ThumbnailPickerView(items: [
ThumbnailPickerView.Item(value: true, name: "create_secret_require_authentication_title", description: "create_secret_require_authentication_description", thumbnail: AuthenticationView()),
ThumbnailPickerView.Item(value: false, name: "create_secret_notify_title",
description: "create_secret_notify_description",
thumbnail: NotificationView())
], selection: $requiresAuthentication)
} }
} }
HStack { HStack {
Spacer() Spacer()
Button("create_secret_cancel_button") { Button("Cancel") {
showing = false showing = false
} }
.keyboardShortcut(.cancelAction) .keyboardShortcut(.cancelAction)
Button("create_secret_create_button", action: save) Button("Create", action: save)
.disabled(name.isEmpty) .disabled(name.isEmpty)
.keyboardShortcut(.defaultAction) .keyboardShortcut(.defaultAction)
} }
@ -45,206 +51,7 @@ struct CreateSecretView<StoreType: SecretStoreModifiable>: View {
} }
func save() { func save() {
Task { try! store.create(name: name, requiresAuthentication: requiresAuthentication)
try! await store.create(name: name, requiresAuthentication: requiresAuthentication) showing = false
showing = false
}
}
}
struct ThumbnailPickerView<ValueType: Hashable>: View {
private let items: [Item<ValueType>]
@Binding var selection: ValueType
init(items: [ThumbnailPickerView<ValueType>.Item<ValueType>], selection: Binding<ValueType>) {
self.items = items
_selection = selection
}
var body: some View {
HStack(alignment: .top) {
ForEach(items) { item in
VStack(alignment: .leading, spacing: 15) {
item.thumbnail
.frame(height: 200)
.overlay(RoundedRectangle(cornerRadius: 10)
.stroke(lineWidth: item.value == selection ? 15 : 0))
.clipShape(RoundedRectangle(cornerRadius: 10, style: .continuous))
.foregroundColor(.accentColor)
VStack(alignment: .leading, spacing: 5) {
Text(item.name)
.bold()
Text(item.description)
.fixedSize(horizontal: false, vertical: true)
}
}
.frame(width: 250)
.onTapGesture {
withAnimation(.spring()) {
selection = item.value
}
}
}
.padding(5)
}
}
}
extension ThumbnailPickerView {
struct Item<InnerValueType: Hashable>: Identifiable {
let id = UUID()
let value: InnerValueType
let name: LocalizedStringKey
let description: LocalizedStringKey
let thumbnail: AnyView
init<ViewType: View>(value: InnerValueType, name: LocalizedStringKey, description: LocalizedStringKey, thumbnail: ViewType) {
self.value = value
self.name = name
self.description = description
self.thumbnail = AnyView(thumbnail)
}
}
}
@MainActor class SystemBackground: ObservableObject {
static let shared = SystemBackground()
@Published var image: NSImage?
private init() {
if let mainScreen = NSScreen.main, let imageURL = NSWorkspace.shared.desktopImageURL(for: mainScreen) {
image = NSImage(contentsOf: imageURL)
} else {
image = nil
}
}
}
struct SystemBackgroundView: View {
let anchor: UnitPoint
var body: some View {
if let image = SystemBackground.shared.image {
Image(nsImage: image)
.resizable()
.scaleEffect(3, anchor: anchor)
.clipped()
.allowsHitTesting(false)
} else {
Rectangle()
.foregroundColor(Color(.systemPurple))
}
} }
} }
struct AuthenticationView: View {
var body: some View {
ZStack {
SystemBackgroundView(anchor: .center)
GeometryReader { geometry in
VStack {
Image(systemName: "touchid")
.resizable()
.aspectRatio(contentMode: .fit)
.foregroundColor(Color(.systemRed))
Text(verbatim: "Touch ID Prompt")
.font(.headline)
.foregroundColor(.primary)
.redacted(reason: .placeholder)
VStack {
Text(verbatim: "Touch ID Detail prompt.Detail two.")
.font(.caption2)
.foregroundColor(.primary)
Text(verbatim: "Touch ID Detail prompt.Detail two.")
.font(.caption2)
.foregroundColor(.primary)
}
.redacted(reason: .placeholder)
RoundedRectangle(cornerRadius: 5)
.frame(width: geometry.size.width, height: 20, alignment: .center)
.foregroundColor(.accentColor)
RoundedRectangle(cornerRadius: 5)
.frame(width: geometry.size.width, height: 20, alignment: .center)
.foregroundColor(Color(.unemphasizedSelectedContentBackgroundColor))
}
}
.padding()
.frame(width: 150)
.background(
RoundedRectangle(cornerRadius: 15)
.foregroundStyle(.ultraThickMaterial)
)
.padding()
}
}
}
struct NotificationView: View {
var body: some View {
ZStack {
SystemBackgroundView(anchor: .topTrailing)
VStack {
Rectangle()
.background(Color.clear)
.foregroundStyle(.thinMaterial)
.frame(height: 35)
VStack {
HStack {
Spacer()
HStack {
Image(nsImage: NSApplication.shared.applicationIconImage)
.resizable()
.frame(width: 64, height: 64)
.foregroundColor(.primary)
VStack(alignment: .leading) {
Text(verbatim: "Secretive")
.font(.title)
.foregroundColor(.primary)
Text(verbatim: "Secretive wants to sign")
.font(.body)
.foregroundColor(.primary)
}
}.padding()
.redacted(reason: .placeholder)
.background(
RoundedRectangle(cornerRadius: 15)
.foregroundStyle(.ultraThickMaterial)
)
}
Spacer()
}
.padding()
}
}
}
}
//#if DEBUG
//
//struct CreateSecretView_Previews: PreviewProvider {
//
// static var previews: some View {
// Group {
// CreateSecretView(store: Preview.StoreModifiable(), showing: .constant(true))
// AuthenticationView().environment(\.colorScheme, .dark)
// AuthenticationView().environment(\.colorScheme, .light)
// NotificationView().environment(\.colorScheme, .dark)
// NotificationView().environment(\.colorScheme, .light)
// }
// }
//}
//
//#endif

View File

@ -3,7 +3,7 @@ import SecretKit
struct DeleteSecretView<StoreType: SecretStoreModifiable>: View { struct DeleteSecretView<StoreType: SecretStoreModifiable>: View {
@State var store: StoreType @ObservedObject var store: StoreType
let secret: StoreType.SecretType let secret: StoreType.SecretType
var dismissalBlock: (Bool) -> () var dismissalBlock: (Bool) -> ()
@ -18,24 +18,25 @@ struct DeleteSecretView<StoreType: SecretStoreModifiable>: View {
.padding() .padding()
VStack { VStack {
HStack { HStack {
Text("delete_confirmation_title_\(secret.name)").bold() Text("Delete \(secret.name)?").bold()
Spacer() Spacer()
} }
HStack { HStack {
Text("delete_confirmation_description_\(secret.name)_\(secret.name)") Text("If you delete \(secret.name), you will not be able to recover it. Type \"\(secret.name)\" to confirm.")
Spacer() Spacer()
} }
HStack { HStack {
Text("delete_confirmation_confirm_name_label") Text("Confirm Name:")
TextField(secret.name, text: $confirm) TextField(secret.name, text: $confirm)
} }
} }
} }
HStack { HStack {
Spacer() Spacer()
Button("delete_confirmation_delete_button", action: delete) Button("Delete", action: delete)
.disabled(confirm != secret.name) .disabled(confirm != secret.name)
Button("delete_confirmation_cancel_button") { .keyboardShortcut(.delete)
Button("Don't Delete") {
dismissalBlock(false) dismissalBlock(false)
} }
.keyboardShortcut(.cancelAction) .keyboardShortcut(.cancelAction)
@ -49,10 +50,8 @@ struct DeleteSecretView<StoreType: SecretStoreModifiable>: View {
} }
func delete() { func delete() {
Task { try! store.delete(secret: secret)
try! await store.delete(secret: secret) dismissalBlock(true)
dismissalBlock(true)
}
} }
} }

View File

@ -3,17 +3,17 @@ import SecretKit
struct EmptyStoreView: View { struct EmptyStoreView: View {
@State var store: AnySecretStore @ObservedObject var store: AnySecretStore
@Binding var activeSecret: AnySecret.ID? @Binding var activeSecret: AnySecret.ID?
var body: some View { var body: some View {
if store is AnySecretStoreModifiable { if store is AnySecretStoreModifiable {
NavigationLink(destination: EmptyStoreModifiableView(), tag: Constants.emptyStoreModifiableTag, selection: $activeSecret) { NavigationLink(destination: EmptyStoreModifiableView(), tag: Constants.emptyStoreModifiableTag, selection: $activeSecret) {
Text("empty_store_modifiable_title") Text("No Secrets")
} }
} else { } else {
NavigationLink(destination: EmptyStoreImmutableView(), tag: Constants.emptyStoreTag, selection: $activeSecret) { NavigationLink(destination: EmptyStoreImmutableView(), tag: Constants.emptyStoreTag, selection: $activeSecret) {
Text("empty_store_nonmodifiable_title") Text("No Secrets")
} }
} }
} }
@ -22,8 +22,8 @@ struct EmptyStoreView: View {
extension EmptyStoreView { extension EmptyStoreView {
enum Constants { enum Constants {
static let emptyStoreModifiableTag = "emptyStoreModifiableTag" static let emptyStoreModifiableTag: AnyHashable = "emptyStoreModifiableTag"
static let emptyStoreTag = "emptyStoreTag" static let emptyStoreTag: AnyHashable = "emptyStoreModifiableTag"
} }
} }
@ -32,9 +32,9 @@ struct EmptyStoreImmutableView: View {
var body: some View { var body: some View {
VStack { VStack {
Text("empty_store_nonmodifiable_title").bold() Text("No Secrets").bold()
Text("empty_store_nonmodifiable_description") Text("Use your Smart Card's management tool to create a secret.")
Text("empty_store_nonmodifiable_supported_key_types") Text("Secretive only supports Elliptic Curve keys.")
}.frame(maxWidth: .infinity, maxHeight: .infinity) }.frame(maxWidth: .infinity, maxHeight: .infinity)
} }
@ -63,8 +63,8 @@ struct EmptyStoreModifiableView: View {
path.addLine(to: CGPoint(x: g.size.width - 3, y: 0)) path.addLine(to: CGPoint(x: g.size.width - 3, y: 0))
}.fill() }.fill()
}.frame(height: (windowGeometry.size.height/2) - 20).padding() }.frame(height: (windowGeometry.size.height/2) - 20).padding()
Text("empty_store_modifiable_click_here_title").bold() Text("No Secrets").bold()
Text("empty_store_modifiable_click_here_description") Text("Create a new one by clicking here.")
Spacer() Spacer()
}.frame(maxWidth: .infinity, maxHeight: .infinity) }.frame(maxWidth: .infinity, maxHeight: .infinity)
} }

View File

@ -4,10 +4,9 @@ struct NoStoresView: View {
var body: some View { var body: some View {
VStack { VStack {
Text("no_secure_storage_title") Text("No Secure Storage Available").bold()
.bold() Text("Your Mac doesn't have a Secure Enclave, and there's not a compatible Smart Card inserted.")
Text("no_secure_storage_description") Link("If you're looking to add one to your Mac, the YubiKey 5 Series are great.", destination: URL(string: "https://www.yubico.com/products/compare-yubikey-5-series/")!)
Link("no_secure_storage_yubico_link", destination: URL(string: "https://www.yubico.com/products/compare-yubikey-5-series/")!)
}.padding() }.padding()
} }

View File

@ -3,7 +3,7 @@ import SecretKit
struct RenameSecretView<StoreType: SecretStoreModifiable>: View { struct RenameSecretView<StoreType: SecretStoreModifiable>: View {
@State var store: StoreType @ObservedObject var store: StoreType
let secret: StoreType.SecretType let secret: StoreType.SecretType
var dismissalBlock: (_ renamed: Bool) -> () var dismissalBlock: (_ renamed: Bool) -> ()
@ -18,7 +18,7 @@ struct RenameSecretView<StoreType: SecretStoreModifiable>: View {
.padding() .padding()
VStack { VStack {
HStack { HStack {
Text("rename_title_\(secret.name)") Text("Type your new name for \"\(secret.name)\" below.")
Spacer() Spacer()
} }
HStack { HStack {
@ -28,10 +28,10 @@ struct RenameSecretView<StoreType: SecretStoreModifiable>: View {
} }
HStack { HStack {
Spacer() Spacer()
Button("rename_rename_button", action: rename) Button("Rename", action: rename)
.disabled(newName.count == 0) .disabled(newName.count == 0)
.keyboardShortcut(.return) .keyboardShortcut(.return)
Button("rename_cancel_button") { Button("Cancel") {
dismissalBlock(false) dismissalBlock(false)
}.keyboardShortcut(.cancelAction) }.keyboardShortcut(.cancelAction)
} }
@ -44,9 +44,7 @@ struct RenameSecretView<StoreType: SecretStoreModifiable>: View {
} }
func rename() { func rename() {
Task { try? store.update(secret: secret, name: newName)
try? await store.update(secret: secret, name: newName) dismissalBlock(true)
dismissalBlock(true)
}
} }
} }

View File

@ -12,16 +12,16 @@ struct SecretDetailView<SecretType: Secret>: View {
ScrollView { ScrollView {
Form { Form {
Section { Section {
CopyableView(title: "secret_detail_sha256_fingerprint_label", image: Image(systemName: "touchid"), text: keyWriter.openSSHSHA256Fingerprint(secret: secret)) CopyableView(title: "SHA256 Fingerprint", image: Image(systemName: "touchid"), text: keyWriter.openSSHSHA256Fingerprint(secret: secret))
Spacer() Spacer()
.frame(height: 20) .frame(height: 20)
CopyableView(title: "secret_detail_md5_fingerprint_label", image: Image(systemName: "touchid"), text: keyWriter.openSSHMD5Fingerprint(secret: secret)) CopyableView(title: "MD5 Fingerprint", image: Image(systemName: "touchid"), text: keyWriter.openSSHMD5Fingerprint(secret: secret))
Spacer() Spacer()
.frame(height: 20) .frame(height: 20)
CopyableView(title: "secret_detail_public_key_label", image: Image(systemName: "key"), text: keyString) CopyableView(title: "Public Key", image: Image(systemName: "key"), text: keyString)
Spacer() Spacer()
.frame(height: 20) .frame(height: 20)
CopyableView(title: "secret_detail_public_key_path_label", image: Image(systemName: "lock.doc"), text: publicKeyFileStoreController.publicKeyPath(for: secret)) CopyableView(title: "Public Key Path", image: Image(systemName: "lock.doc"), text: publicKeyFileStoreController.path(for: secret))
Spacer() Spacer()
} }
} }
@ -47,12 +47,12 @@ struct SecretDetailView<SecretType: Secret>: View {
} }
//#if DEBUG #if DEBUG
//
//struct SecretDetailView_Previews: PreviewProvider { struct SecretDetailView_Previews: PreviewProvider {
// static var previews: some View { static var previews: some View {
// SecretDetailView(secret: Preview.Store(numberOfRandomSecrets: 1).secrets[0]) SecretDetailView(secret: Preview.Store(numberOfRandomSecrets: 1).secrets[0])
// } }
//} }
//
//#endif #endif

View File

@ -3,7 +3,7 @@ import SecretKit
struct SecretListItemView: View { struct SecretListItemView: View {
@State var store: AnySecretStore @ObservedObject var store: AnySecretStore
var secret: AnySecret var secret: AnySecret
@Binding var activeSecret: AnySecret.ID? @Binding var activeSecret: AnySecret.ID?
@ -20,23 +20,14 @@ struct SecretListItemView: View {
) )
return NavigationLink(destination: SecretDetailView(secret: secret), tag: secret.id, selection: $activeSecret) { return NavigationLink(destination: SecretDetailView(secret: secret), tag: secret.id, selection: $activeSecret) {
if secret.requiresAuthentication { Text(secret.name)
HStack { }.contextMenu {
Text(secret.name)
Spacer()
Image(systemName: "lock")
}
} else {
Text(secret.name)
}
}
.contextMenu {
if store is AnySecretStoreModifiable { if store is AnySecretStoreModifiable {
Button(action: { isRenaming = true }) { Button(action: { isRenaming = true }) {
Text("secret_list_rename_button") Text("Rename")
} }
Button(action: { isDeleting = true }) { Button(action: { isDeleting = true }) {
Text("secret_list_delete_button") Text("Delete")
} }
} }
} }

View File

@ -26,7 +26,7 @@ struct SetupView: View {
} }
} }
} }
.frame(minWidth: 500, idealWidth: 500, minHeight: 500, idealHeight: 500) .frame(idealWidth: 500, idealHeight: 500)
} }
@ -61,7 +61,7 @@ struct StepView: View {
Circle() Circle()
.foregroundColor(.green) .foregroundColor(.green)
.frame(width: Constants.circleWidth, height: Constants.circleWidth) .frame(width: Constants.circleWidth, height: Constants.circleWidth)
Text("setup_step_complete_symbol") Text("")
.foregroundColor(.white) .foregroundColor(.white)
.bold() .bold()
} else { } else {
@ -101,14 +101,14 @@ extension StepView {
struct SetupStepView<Content> : View where Content : View { struct SetupStepView<Content> : View where Content : View {
let title: LocalizedStringKey let title: String
let image: Image let image: Image
let bodyText: LocalizedStringKey let bodyText: String
let buttonTitle: LocalizedStringKey let buttonTitle: String
let buttonAction: () -> Void let buttonAction: () -> Void
let content: Content let content: Content
init(title: LocalizedStringKey, image: Image, bodyText: LocalizedStringKey, buttonTitle: LocalizedStringKey, buttonAction: @escaping () -> Void = {}, @ViewBuilder content: () -> Content) { init(title: String, image: Image, bodyText: String, buttonTitle: String, buttonAction: @escaping () -> Void = {}, @ViewBuilder content: () -> Content) {
self.title = title self.title = title
self.image = image self.image = image
self.bodyText = bodyText self.bodyText = bodyText
@ -145,21 +145,19 @@ struct SecretAgentSetupView: View {
let buttonAction: () -> Void let buttonAction: () -> Void
var body: some View { var body: some View {
SetupStepView(title: "setup_agent_title", SetupStepView(title: "Setup Secret Agent",
image: Image(nsImage: NSApplication.shared.applicationIconImage), image: Image(nsImage: NSApplication.shared.applicationIconImage),
bodyText: "setup_agent_description", bodyText: "Secretive needs to set up a helper app to work properly. It will sign requests from SSH clients in the background, so you don't need to keep the main Secretive app open.",
buttonTitle: "setup_agent_install_button", buttonTitle: "Install",
buttonAction: install) { buttonAction: install) {
Text("setup_agent_activity_monitor_description") (Text("This helper app is called ") + Text("Secret Agent").bold().underline() + Text(" and you may see it in Activity Manager from time to time."))
.multilineTextAlignment(.center) .multilineTextAlignment(.center)
} }
} }
func install() { func install() {
Task { LaunchAgentController().install()
await LaunchAgentController().install() buttonAction()
buttonAction()
}
} }
} }
@ -172,12 +170,12 @@ struct SSHAgentSetupView: View {
@State private var selectedShellInstruction: ShellConfigInstruction = controller.shellInstructions.first! @State private var selectedShellInstruction: ShellConfigInstruction = controller.shellInstructions.first!
var body: some View { var body: some View {
SetupStepView(title: "setup_ssh_title", SetupStepView(title: "Configure your SSH Agent",
image: Image(systemName: "terminal"), image: Image(systemName: "terminal"),
bodyText: "setup_ssh_description", bodyText: "Add this line to your shell config telling SSH to talk to Secret Agent when it wants to authenticate. Secretive can either do this for you automatically, or you can copy and paste this into your config file.",
buttonTitle: "setup_ssh_added_manually_button", buttonTitle: "I Added it Manually",
buttonAction: buttonAction) { buttonAction: buttonAction) {
Link("setup_third_party_faq_link", destination: URL(string: "https://github.com/maxgoedjen/secretive/blob/main/APP_CONFIG.md")!) Link("If you're trying to set up a third party app, check out the FAQ.", destination: URL(string: "https://github.com/maxgoedjen/secretive/blob/main/APP_CONFIG.md")!)
Picker(selection: $selectedShellInstruction, label: EmptyView()) { Picker(selection: $selectedShellInstruction, label: EmptyView()) {
ForEach(SSHAgentSetupView.controller.shellInstructions) { instruction in ForEach(SSHAgentSetupView.controller.shellInstructions) { instruction in
Text(instruction.shell) Text(instruction.shell)
@ -185,8 +183,8 @@ struct SSHAgentSetupView: View {
.padding() .padding()
} }
}.pickerStyle(SegmentedPickerStyle()) }.pickerStyle(SegmentedPickerStyle())
CopyableView(title: "setup_ssh_add_to_config_button_\(selectedShellInstruction.shellConfigPath)", image: Image(systemName: "greaterthan.square"), text: selectedShellInstruction.text) CopyableView(title: "Add to \(selectedShellInstruction.shellConfigPath)", image: Image(systemName: "greaterthan.square"), text: selectedShellInstruction.text)
Button("setup_ssh_add_for_me_button") { Button("Add it For Me") {
let controller = ShellConfigurationController() let controller = ShellConfigurationController()
if controller.addToShell(shellInstructions: selectedShellInstruction) { if controller.addToShell(shellInstructions: selectedShellInstruction) {
buttonAction() buttonAction()
@ -216,12 +214,12 @@ struct UpdaterExplainerView: View {
let buttonAction: () -> Void let buttonAction: () -> Void
var body: some View { var body: some View {
SetupStepView(title: "setup_updates_title", SetupStepView(title: "Updates",
image: Image(systemName: "dot.radiowaves.left.and.right"), image: Image(systemName: "dot.radiowaves.left.and.right"),
bodyText: "setup_updates_description", bodyText: "Secretive will periodically check with GitHub to see if there's a new release. If you see any network requests to GitHub, that's why.",
buttonTitle: "setup_updates_ok", buttonTitle: "Okay",
buttonAction: buttonAction) { buttonAction: buttonAction) {
Link("setup_updates_readmore", destination: SetupView.Constants.updaterFAQURL) Link("Read more about this here.", destination: SetupView.Constants.updaterFAQURL)
} }
} }

View File

@ -1,19 +1,20 @@
import SwiftUI import SwiftUI
import Combine
import SecretKit import SecretKit
struct StoreListView: View { struct StoreListView: View {
@Binding var activeSecret: AnySecret.ID? @Binding var showingCreation: Bool
@Environment(SecretStoreList.self) private var storeList: SecretStoreList @State private var activeSecret: AnySecret.ID?
@EnvironmentObject private var storeList: SecretStoreList
private func secretDeleted(secret: AnySecret) { private func secretDeleted(secret: AnySecret) {
activeSecret = nextDefaultSecret activeSecret = nextDefaultSecret
} }
private func secretRenamed(secret: AnySecret) { private func secretRenamed(secret: AnySecret) {
activeSecret = secret.id activeSecret = nextDefaultSecret
} }
var body: some View { var body: some View {

View File

@ -1,37 +0,0 @@
import SwiftUI
struct ToolbarButtonStyle: ButtonStyle {
private let lightColor: Color
private let darkColor: Color
@Environment(\.colorScheme) var colorScheme
@State var hovering = false
init(color: Color) {
self.lightColor = color
self.darkColor = color
}
init(lightColor: Color, darkColor: Color) {
self.lightColor = lightColor
self.darkColor = darkColor
}
func makeBody(configuration: Configuration) -> some View {
configuration.label
.padding(EdgeInsets(top: 6, leading: 8, bottom: 6, trailing: 8))
.background(colorScheme == .light ? lightColor : darkColor)
.foregroundColor(.white)
.clipShape(RoundedRectangle(cornerRadius: 5))
.overlay(
RoundedRectangle(cornerRadius: 5)
.stroke(colorScheme == .light ? .black.opacity(0.15) : .white.opacity(0.15), lineWidth: 1)
.background(hovering ? (colorScheme == .light ? .black.opacity(0.1) : .white.opacity(0.05)) : Color.clear)
)
.onHover { hovering in
withAnimation {
self.hovering = hovering
}
}
}
}

View File

@ -1,30 +1,28 @@
import SwiftUI import SwiftUI
import Brief import Brief
struct UpdateDetailView<UpdaterType: Updater>: View { struct UpdateDetailView<UpdaterType: UpdateChecker>: View {
@Environment(UpdaterType.self) var updater: UpdaterType @EnvironmentObject var updater: UpdaterType
let update: Release let update: Release
var body: some View { var body: some View {
VStack { VStack {
Text("update_version_name_\(update.name)").font(.title) Text("Secretive \(update.name)").font(.title)
GroupBox(label: Text("update_release_notes_title")) { GroupBox(label: Text("Release Notes")) {
ScrollView { ScrollView {
attributedBody attributedBody
} }
} }
HStack { HStack {
if !update.critical { if !update.critical {
Button("update_ignore_button") { Button("Ignore") {
Task { updater.ignore(release: update)
await updater.ignore(release: update)
}
} }
Spacer() Spacer()
} }
Button("update_update_button") { Button("Update") {
NSWorkspace.shared.open(update.html_url) NSWorkspace.shared.open(update.html_url)
} }
.keyboardShortcut(.defaultAction) .keyboardShortcut(.defaultAction)
@ -36,24 +34,24 @@ struct UpdateDetailView<UpdaterType: Updater>: View {
} }
var attributedBody: Text { var attributedBody: Text {
var text = Text(verbatim: "") var text = Text("")
for line in update.body.split(whereSeparator: \.isNewline) { for line in update.body.split(whereSeparator: \.isNewline) {
let attributed: Text let attributed: Text
let split = line.split(separator: " ") let split = line.split(separator: " ")
let unprefixed = split.dropFirst().joined(separator: " ") let unprefixed = split.dropFirst().joined()
if let prefix = split.first { if let prefix = split.first {
switch prefix { switch prefix {
case "#": case "#":
attributed = Text(unprefixed).font(.title) + Text(verbatim: "\n") attributed = Text(unprefixed).font(.title) + Text("\n")
case "##": case "##":
attributed = Text(unprefixed).font(.title2) + Text(verbatim: "\n") attributed = Text(unprefixed).font(.title2) + Text("\n")
case "###": case "###":
attributed = Text(unprefixed).font(.title3) + Text(verbatim: "\n") attributed = Text(unprefixed).font(.title3) + Text("\n")
default: default:
attributed = Text(line) + Text(verbatim: "\n\n") attributed = Text(line) + Text("\n\n")
} }
} else { } else {
attributed = Text(line) + Text(verbatim: "\n\n") attributed = Text(line) + Text("\n\n")
} }
text = text + attributed text = text + attributed
} }

View File

@ -0,0 +1,22 @@
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd">
<plist version="1.0">
<dict>
<key>CFBundleDevelopmentRegion</key>
<string>$(DEVELOPMENT_LANGUAGE)</string>
<key>CFBundleExecutable</key>
<string>$(EXECUTABLE_NAME)</string>
<key>CFBundleIdentifier</key>
<string>$(PRODUCT_BUNDLE_IDENTIFIER)</string>
<key>CFBundleInfoDictionaryVersion</key>
<string>6.0</string>
<key>CFBundleName</key>
<string>$(PRODUCT_NAME)</string>
<key>CFBundlePackageType</key>
<string>$(PRODUCT_BUNDLE_PACKAGE_TYPE)</string>
<key>CFBundleShortVersionString</key>
<string>1.0</string>
<key>CFBundleVersion</key>
<string>1</string>
</dict>
</plist>

View File

@ -0,0 +1,20 @@
import XCTest
@testable import Secretive
class SecretiveTests: XCTestCase {
override func setUp() {
// Put setup code here. This method is called before the invocation of each test method in the class.
}
override func tearDown() {
// Put teardown code here. This method is called after the invocation of each test method in the class.
}
func testExample() {
// This is an example of a functional test case.
// Use XCTAssert and related functions to verify your tests produce the correct results.
}
}

View File

@ -0,0 +1,11 @@
{
"colors" : [
{
"idiom" : "universal"
}
],
"info" : {
"author" : "xcode",
"version" : 1
}
}

View File

@ -0,0 +1,60 @@
{
"images" : [
{
"idiom" : "mac",
"scale" : "1x",
"size" : "16x16"
},
{
"idiom" : "mac",
"scale" : "2x",
"size" : "16x16"
},
{
"idiom" : "mac",
"scale" : "1x",
"size" : "32x32"
},
{
"idiom" : "mac",
"scale" : "2x",
"size" : "32x32"
},
{
"idiom" : "mac",
"scale" : "1x",
"size" : "128x128"
},
{
"idiom" : "mac",
"scale" : "2x",
"size" : "128x128"
},
{
"filename" : "Mac Icon.png",
"idiom" : "mac",
"scale" : "1x",
"size" : "256x256"
},
{
"filename" : "Mac Icon@0.25x.png",
"idiom" : "mac",
"scale" : "2x",
"size" : "256x256"
},
{
"idiom" : "mac",
"scale" : "1x",
"size" : "512x512"
},
{
"idiom" : "mac",
"scale" : "2x",
"size" : "512x512"
}
],
"info" : {
"author" : "xcode",
"version" : 1
}
}

Binary file not shown.

After

Width:  |  Height:  |  Size: 16 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 40 KiB

View File

@ -0,0 +1,6 @@
{
"info" : {
"author" : "xcode",
"version" : 1
}
}

View File

@ -0,0 +1,8 @@
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd">
<plist version="1.0">
<dict>
<key>LSUIElement</key>
<false/>
</dict>
</plist>

View File

@ -0,0 +1,683 @@
<?xml version="1.0" encoding="UTF-8"?>
<document type="com.apple.InterfaceBuilder3.Cocoa.Storyboard.XIB" version="3.0" toolsVersion="20036.2" targetRuntime="MacOSX.Cocoa" propertyAccessControl="none" useAutolayout="YES">
<dependencies>
<plugIn identifier="com.apple.InterfaceBuilder.CocoaPlugin" version="20036.2"/>
</dependencies>
<scenes>
<!--Application-->
<scene sceneID="JPo-4y-FX3">
<objects>
<application id="hnw-xV-0zn" sceneMemberID="viewController">
<menu key="mainMenu" title="Main Menu" systemMenu="main" id="AYu-sK-qS6">
<items>
<menuItem title="SecretiveUpdater" id="1Xt-HY-uBw">
<modifierMask key="keyEquivalentModifierMask"/>
<menu key="submenu" title="SecretiveUpdater" systemMenu="apple" id="uQy-DD-JDr">
<items>
<menuItem title="About SecretiveUpdater" id="5kV-Vb-QxS">
<modifierMask key="keyEquivalentModifierMask"/>
<connections>
<action selector="orderFrontStandardAboutPanel:" target="Ady-hI-5gd" id="Exp-CZ-Vem"/>
</connections>
</menuItem>
<menuItem isSeparatorItem="YES" id="VOq-y0-SEH"/>
<menuItem title="Preferences…" keyEquivalent="," id="BOF-NM-1cW"/>
<menuItem isSeparatorItem="YES" id="wFC-TO-SCJ"/>
<menuItem title="Services" id="NMo-om-nkz">
<modifierMask key="keyEquivalentModifierMask"/>
<menu key="submenu" title="Services" systemMenu="services" id="hz9-B4-Xy5"/>
</menuItem>
<menuItem isSeparatorItem="YES" id="4je-JR-u6R"/>
<menuItem title="Hide SecretiveUpdater" keyEquivalent="h" id="Olw-nP-bQN">
<connections>
<action selector="hide:" target="Ady-hI-5gd" id="PnN-Uc-m68"/>
</connections>
</menuItem>
<menuItem title="Hide Others" keyEquivalent="h" id="Vdr-fp-XzO">
<modifierMask key="keyEquivalentModifierMask" option="YES" command="YES"/>
<connections>
<action selector="hideOtherApplications:" target="Ady-hI-5gd" id="VT4-aY-XCT"/>
</connections>
</menuItem>
<menuItem title="Show All" id="Kd2-mp-pUS">
<modifierMask key="keyEquivalentModifierMask"/>
<connections>
<action selector="unhideAllApplications:" target="Ady-hI-5gd" id="Dhg-Le-xox"/>
</connections>
</menuItem>
<menuItem isSeparatorItem="YES" id="kCx-OE-vgT"/>
<menuItem title="Quit SecretiveUpdater" keyEquivalent="q" id="4sb-4s-VLi">
<connections>
<action selector="terminate:" target="Ady-hI-5gd" id="Te7-pn-YzF"/>
</connections>
</menuItem>
</items>
</menu>
</menuItem>
<menuItem title="File" id="dMs-cI-mzQ">
<modifierMask key="keyEquivalentModifierMask"/>
<menu key="submenu" title="File" id="bib-Uj-vzu">
<items>
<menuItem title="New" keyEquivalent="n" id="Was-JA-tGl">
<connections>
<action selector="newDocument:" target="Ady-hI-5gd" id="4Si-XN-c54"/>
</connections>
</menuItem>
<menuItem title="Open…" keyEquivalent="o" id="IAo-SY-fd9">
<connections>
<action selector="openDocument:" target="Ady-hI-5gd" id="bVn-NM-KNZ"/>
</connections>
</menuItem>
<menuItem title="Open Recent" id="tXI-mr-wws">
<modifierMask key="keyEquivalentModifierMask"/>
<menu key="submenu" title="Open Recent" systemMenu="recentDocuments" id="oas-Oc-fiZ">
<items>
<menuItem title="Clear Menu" id="vNY-rz-j42">
<modifierMask key="keyEquivalentModifierMask"/>
<connections>
<action selector="clearRecentDocuments:" target="Ady-hI-5gd" id="Daa-9d-B3U"/>
</connections>
</menuItem>
</items>
</menu>
</menuItem>
<menuItem isSeparatorItem="YES" id="m54-Is-iLE"/>
<menuItem title="Close" keyEquivalent="w" id="DVo-aG-piG">
<connections>
<action selector="performClose:" target="Ady-hI-5gd" id="HmO-Ls-i7Q"/>
</connections>
</menuItem>
<menuItem title="Save…" keyEquivalent="s" id="pxx-59-PXV">
<connections>
<action selector="saveDocument:" target="Ady-hI-5gd" id="teZ-XB-qJY"/>
</connections>
</menuItem>
<menuItem title="Save As…" keyEquivalent="S" id="Bw7-FT-i3A">
<connections>
<action selector="saveDocumentAs:" target="Ady-hI-5gd" id="mDf-zr-I0C"/>
</connections>
</menuItem>
<menuItem title="Revert to Saved" keyEquivalent="r" id="KaW-ft-85H">
<connections>
<action selector="revertDocumentToSaved:" target="Ady-hI-5gd" id="iJ3-Pv-kwq"/>
</connections>
</menuItem>
<menuItem isSeparatorItem="YES" id="aJh-i4-bef"/>
<menuItem title="Page Setup…" keyEquivalent="P" id="qIS-W8-SiK">
<modifierMask key="keyEquivalentModifierMask" shift="YES" command="YES"/>
<connections>
<action selector="runPageLayout:" target="Ady-hI-5gd" id="Din-rz-gC5"/>
</connections>
</menuItem>
<menuItem title="Print…" keyEquivalent="p" id="aTl-1u-JFS">
<connections>
<action selector="print:" target="Ady-hI-5gd" id="qaZ-4w-aoO"/>
</connections>
</menuItem>
</items>
</menu>
</menuItem>
<menuItem title="Edit" id="5QF-Oa-p0T">
<modifierMask key="keyEquivalentModifierMask"/>
<menu key="submenu" title="Edit" id="W48-6f-4Dl">
<items>
<menuItem title="Undo" keyEquivalent="z" id="dRJ-4n-Yzg">
<connections>
<action selector="undo:" target="Ady-hI-5gd" id="M6e-cu-g7V"/>
</connections>
</menuItem>
<menuItem title="Redo" keyEquivalent="Z" id="6dh-zS-Vam">
<connections>
<action selector="redo:" target="Ady-hI-5gd" id="oIA-Rs-6OD"/>
</connections>
</menuItem>
<menuItem isSeparatorItem="YES" id="WRV-NI-Exz"/>
<menuItem title="Cut" keyEquivalent="x" id="uRl-iY-unG">
<connections>
<action selector="cut:" target="Ady-hI-5gd" id="YJe-68-I9s"/>
</connections>
</menuItem>
<menuItem title="Copy" keyEquivalent="c" id="x3v-GG-iWU">
<connections>
<action selector="copy:" target="Ady-hI-5gd" id="G1f-GL-Joy"/>
</connections>
</menuItem>
<menuItem title="Paste" keyEquivalent="v" id="gVA-U4-sdL">
<connections>
<action selector="paste:" target="Ady-hI-5gd" id="UvS-8e-Qdg"/>
</connections>
</menuItem>
<menuItem title="Paste and Match Style" keyEquivalent="V" id="WeT-3V-zwk">
<modifierMask key="keyEquivalentModifierMask" option="YES" command="YES"/>
<connections>
<action selector="pasteAsPlainText:" target="Ady-hI-5gd" id="cEh-KX-wJQ"/>
</connections>
</menuItem>
<menuItem title="Delete" id="pa3-QI-u2k">
<modifierMask key="keyEquivalentModifierMask"/>
<connections>
<action selector="delete:" target="Ady-hI-5gd" id="0Mk-Ml-PaM"/>
</connections>
</menuItem>
<menuItem title="Select All" keyEquivalent="a" id="Ruw-6m-B2m">
<connections>
<action selector="selectAll:" target="Ady-hI-5gd" id="VNm-Mi-diN"/>
</connections>
</menuItem>
<menuItem isSeparatorItem="YES" id="uyl-h8-XO2"/>
<menuItem title="Find" id="4EN-yA-p0u">
<modifierMask key="keyEquivalentModifierMask"/>
<menu key="submenu" title="Find" id="1b7-l0-nxx">
<items>
<menuItem title="Find…" tag="1" keyEquivalent="f" id="Xz5-n4-O0W">
<connections>
<action selector="performFindPanelAction:" target="Ady-hI-5gd" id="cD7-Qs-BN4"/>
</connections>
</menuItem>
<menuItem title="Find and Replace…" tag="12" keyEquivalent="f" id="YEy-JH-Tfz">
<modifierMask key="keyEquivalentModifierMask" option="YES" command="YES"/>
<connections>
<action selector="performFindPanelAction:" target="Ady-hI-5gd" id="WD3-Gg-5AJ"/>
</connections>
</menuItem>
<menuItem title="Find Next" tag="2" keyEquivalent="g" id="q09-fT-Sye">
<connections>
<action selector="performFindPanelAction:" target="Ady-hI-5gd" id="NDo-RZ-v9R"/>
</connections>
</menuItem>
<menuItem title="Find Previous" tag="3" keyEquivalent="G" id="OwM-mh-QMV">
<connections>
<action selector="performFindPanelAction:" target="Ady-hI-5gd" id="HOh-sY-3ay"/>
</connections>
</menuItem>
<menuItem title="Use Selection for Find" tag="7" keyEquivalent="e" id="buJ-ug-pKt">
<connections>
<action selector="performFindPanelAction:" target="Ady-hI-5gd" id="U76-nv-p5D"/>
</connections>
</menuItem>
<menuItem title="Jump to Selection" keyEquivalent="j" id="S0p-oC-mLd">
<connections>
<action selector="centerSelectionInVisibleArea:" target="Ady-hI-5gd" id="IOG-6D-g5B"/>
</connections>
</menuItem>
</items>
</menu>
</menuItem>
<menuItem title="Spelling and Grammar" id="Dv1-io-Yv7">
<modifierMask key="keyEquivalentModifierMask"/>
<menu key="submenu" title="Spelling" id="3IN-sU-3Bg">
<items>
<menuItem title="Show Spelling and Grammar" keyEquivalent=":" id="HFo-cy-zxI">
<connections>
<action selector="showGuessPanel:" target="Ady-hI-5gd" id="vFj-Ks-hy3"/>
</connections>
</menuItem>
<menuItem title="Check Document Now" keyEquivalent=";" id="hz2-CU-CR7">
<connections>
<action selector="checkSpelling:" target="Ady-hI-5gd" id="fz7-VC-reM"/>
</connections>
</menuItem>
<menuItem isSeparatorItem="YES" id="bNw-od-mp5"/>
<menuItem title="Check Spelling While Typing" id="rbD-Rh-wIN">
<modifierMask key="keyEquivalentModifierMask"/>
<connections>
<action selector="toggleContinuousSpellChecking:" target="Ady-hI-5gd" id="7w6-Qz-0kB"/>
</connections>
</menuItem>
<menuItem title="Check Grammar With Spelling" id="mK6-2p-4JG">
<modifierMask key="keyEquivalentModifierMask"/>
<connections>
<action selector="toggleGrammarChecking:" target="Ady-hI-5gd" id="muD-Qn-j4w"/>
</connections>
</menuItem>
<menuItem title="Correct Spelling Automatically" id="78Y-hA-62v">
<modifierMask key="keyEquivalentModifierMask"/>
<connections>
<action selector="toggleAutomaticSpellingCorrection:" target="Ady-hI-5gd" id="2lM-Qi-WAP"/>
</connections>
</menuItem>
</items>
</menu>
</menuItem>
<menuItem title="Substitutions" id="9ic-FL-obx">
<modifierMask key="keyEquivalentModifierMask"/>
<menu key="submenu" title="Substitutions" id="FeM-D8-WVr">
<items>
<menuItem title="Show Substitutions" id="z6F-FW-3nz">
<modifierMask key="keyEquivalentModifierMask"/>
<connections>
<action selector="orderFrontSubstitutionsPanel:" target="Ady-hI-5gd" id="oku-mr-iSq"/>
</connections>
</menuItem>
<menuItem isSeparatorItem="YES" id="gPx-C9-uUO"/>
<menuItem title="Smart Copy/Paste" id="9yt-4B-nSM">
<modifierMask key="keyEquivalentModifierMask"/>
<connections>
<action selector="toggleSmartInsertDelete:" target="Ady-hI-5gd" id="3IJ-Se-DZD"/>
</connections>
</menuItem>
<menuItem title="Smart Quotes" id="hQb-2v-fYv">
<modifierMask key="keyEquivalentModifierMask"/>
<connections>
<action selector="toggleAutomaticQuoteSubstitution:" target="Ady-hI-5gd" id="ptq-xd-QOA"/>
</connections>
</menuItem>
<menuItem title="Smart Dashes" id="rgM-f4-ycn">
<modifierMask key="keyEquivalentModifierMask"/>
<connections>
<action selector="toggleAutomaticDashSubstitution:" target="Ady-hI-5gd" id="oCt-pO-9gS"/>
</connections>
</menuItem>
<menuItem title="Smart Links" id="cwL-P1-jid">
<modifierMask key="keyEquivalentModifierMask"/>
<connections>
<action selector="toggleAutomaticLinkDetection:" target="Ady-hI-5gd" id="Gip-E3-Fov"/>
</connections>
</menuItem>
<menuItem title="Data Detectors" id="tRr-pd-1PS">
<modifierMask key="keyEquivalentModifierMask"/>
<connections>
<action selector="toggleAutomaticDataDetection:" target="Ady-hI-5gd" id="R1I-Nq-Kbl"/>
</connections>
</menuItem>
<menuItem title="Text Replacement" id="HFQ-gK-NFA">
<modifierMask key="keyEquivalentModifierMask"/>
<connections>
<action selector="toggleAutomaticTextReplacement:" target="Ady-hI-5gd" id="DvP-Fe-Py6"/>
</connections>
</menuItem>
</items>
</menu>
</menuItem>
<menuItem title="Transformations" id="2oI-Rn-ZJC">
<modifierMask key="keyEquivalentModifierMask"/>
<menu key="submenu" title="Transformations" id="c8a-y6-VQd">
<items>
<menuItem title="Make Upper Case" id="vmV-6d-7jI">
<modifierMask key="keyEquivalentModifierMask"/>
<connections>
<action selector="uppercaseWord:" target="Ady-hI-5gd" id="sPh-Tk-edu"/>
</connections>
</menuItem>
<menuItem title="Make Lower Case" id="d9M-CD-aMd">
<modifierMask key="keyEquivalentModifierMask"/>
<connections>
<action selector="lowercaseWord:" target="Ady-hI-5gd" id="iUZ-b5-hil"/>
</connections>
</menuItem>
<menuItem title="Capitalize" id="UEZ-Bs-lqG">
<modifierMask key="keyEquivalentModifierMask"/>
<connections>
<action selector="capitalizeWord:" target="Ady-hI-5gd" id="26H-TL-nsh"/>
</connections>
</menuItem>
</items>
</menu>
</menuItem>
<menuItem title="Speech" id="xrE-MZ-jX0">
<modifierMask key="keyEquivalentModifierMask"/>
<menu key="submenu" title="Speech" id="3rS-ZA-NoH">
<items>
<menuItem title="Start Speaking" id="Ynk-f8-cLZ">
<modifierMask key="keyEquivalentModifierMask"/>
<connections>
<action selector="startSpeaking:" target="Ady-hI-5gd" id="654-Ng-kyl"/>
</connections>
</menuItem>
<menuItem title="Stop Speaking" id="Oyz-dy-DGm">
<modifierMask key="keyEquivalentModifierMask"/>
<connections>
<action selector="stopSpeaking:" target="Ady-hI-5gd" id="dX8-6p-jy9"/>
</connections>
</menuItem>
</items>
</menu>
</menuItem>
</items>
</menu>
</menuItem>
<menuItem title="Format" id="jxT-CU-nIS">
<modifierMask key="keyEquivalentModifierMask"/>
<menu key="submenu" title="Format" id="GEO-Iw-cKr">
<items>
<menuItem title="Font" id="Gi5-1S-RQB">
<modifierMask key="keyEquivalentModifierMask"/>
<menu key="submenu" title="Font" systemMenu="font" id="aXa-aM-Jaq">
<items>
<menuItem title="Show Fonts" keyEquivalent="t" id="Q5e-8K-NDq">
<connections>
<action selector="orderFrontFontPanel:" target="YLy-65-1bz" id="WHr-nq-2xA"/>
</connections>
</menuItem>
<menuItem title="Bold" tag="2" keyEquivalent="b" id="GB9-OM-e27">
<connections>
<action selector="addFontTrait:" target="YLy-65-1bz" id="hqk-hr-sYV"/>
</connections>
</menuItem>
<menuItem title="Italic" tag="1" keyEquivalent="i" id="Vjx-xi-njq">
<connections>
<action selector="addFontTrait:" target="YLy-65-1bz" id="IHV-OB-c03"/>
</connections>
</menuItem>
<menuItem title="Underline" keyEquivalent="u" id="WRG-CD-K1S">
<connections>
<action selector="underline:" target="Ady-hI-5gd" id="FYS-2b-JAY"/>
</connections>
</menuItem>
<menuItem isSeparatorItem="YES" id="5gT-KC-WSO"/>
<menuItem title="Bigger" tag="3" keyEquivalent="+" id="Ptp-SP-VEL">
<connections>
<action selector="modifyFont:" target="YLy-65-1bz" id="Uc7-di-UnL"/>
</connections>
</menuItem>
<menuItem title="Smaller" tag="4" keyEquivalent="-" id="i1d-Er-qST">
<connections>
<action selector="modifyFont:" target="YLy-65-1bz" id="HcX-Lf-eNd"/>
</connections>
</menuItem>
<menuItem isSeparatorItem="YES" id="kx3-Dk-x3B"/>
<menuItem title="Kern" id="jBQ-r6-VK2">
<modifierMask key="keyEquivalentModifierMask"/>
<menu key="submenu" title="Kern" id="tlD-Oa-oAM">
<items>
<menuItem title="Use Default" id="GUa-eO-cwY">
<modifierMask key="keyEquivalentModifierMask"/>
<connections>
<action selector="useStandardKerning:" target="Ady-hI-5gd" id="6dk-9l-Ckg"/>
</connections>
</menuItem>
<menuItem title="Use None" id="cDB-IK-hbR">
<modifierMask key="keyEquivalentModifierMask"/>
<connections>
<action selector="turnOffKerning:" target="Ady-hI-5gd" id="U8a-gz-Maa"/>
</connections>
</menuItem>
<menuItem title="Tighten" id="46P-cB-AYj">
<modifierMask key="keyEquivalentModifierMask"/>
<connections>
<action selector="tightenKerning:" target="Ady-hI-5gd" id="hr7-Nz-8ro"/>
</connections>
</menuItem>
<menuItem title="Loosen" id="ogc-rX-tC1">
<modifierMask key="keyEquivalentModifierMask"/>
<connections>
<action selector="loosenKerning:" target="Ady-hI-5gd" id="8i4-f9-FKE"/>
</connections>
</menuItem>
</items>
</menu>
</menuItem>
<menuItem title="Ligatures" id="o6e-r0-MWq">
<modifierMask key="keyEquivalentModifierMask"/>
<menu key="submenu" title="Ligatures" id="w0m-vy-SC9">
<items>
<menuItem title="Use Default" id="agt-UL-0e3">
<modifierMask key="keyEquivalentModifierMask"/>
<connections>
<action selector="useStandardLigatures:" target="Ady-hI-5gd" id="7uR-wd-Dx6"/>
</connections>
</menuItem>
<menuItem title="Use None" id="J7y-lM-qPV">
<modifierMask key="keyEquivalentModifierMask"/>
<connections>
<action selector="turnOffLigatures:" target="Ady-hI-5gd" id="iX2-gA-Ilz"/>
</connections>
</menuItem>
<menuItem title="Use All" id="xQD-1f-W4t">
<modifierMask key="keyEquivalentModifierMask"/>
<connections>
<action selector="useAllLigatures:" target="Ady-hI-5gd" id="KcB-kA-TuK"/>
</connections>
</menuItem>
</items>
</menu>
</menuItem>
<menuItem title="Baseline" id="OaQ-X3-Vso">
<modifierMask key="keyEquivalentModifierMask"/>
<menu key="submenu" title="Baseline" id="ijk-EB-dga">
<items>
<menuItem title="Use Default" id="3Om-Ey-2VK">
<modifierMask key="keyEquivalentModifierMask"/>
<connections>
<action selector="unscript:" target="Ady-hI-5gd" id="0vZ-95-Ywn"/>
</connections>
</menuItem>
<menuItem title="Superscript" id="Rqc-34-cIF">
<modifierMask key="keyEquivalentModifierMask"/>
<connections>
<action selector="superscript:" target="Ady-hI-5gd" id="3qV-fo-wpU"/>
</connections>
</menuItem>
<menuItem title="Subscript" id="I0S-gh-46l">
<modifierMask key="keyEquivalentModifierMask"/>
<connections>
<action selector="subscript:" target="Ady-hI-5gd" id="Q6W-4W-IGz"/>
</connections>
</menuItem>
<menuItem title="Raise" id="2h7-ER-AoG">
<modifierMask key="keyEquivalentModifierMask"/>
<connections>
<action selector="raiseBaseline:" target="Ady-hI-5gd" id="4sk-31-7Q9"/>
</connections>
</menuItem>
<menuItem title="Lower" id="1tx-W0-xDw">
<modifierMask key="keyEquivalentModifierMask"/>
<connections>
<action selector="lowerBaseline:" target="Ady-hI-5gd" id="OF1-bc-KW4"/>
</connections>
</menuItem>
</items>
</menu>
</menuItem>
<menuItem isSeparatorItem="YES" id="Ndw-q3-faq"/>
<menuItem title="Show Colors" keyEquivalent="C" id="bgn-CT-cEk">
<connections>
<action selector="orderFrontColorPanel:" target="Ady-hI-5gd" id="mSX-Xz-DV3"/>
</connections>
</menuItem>
<menuItem isSeparatorItem="YES" id="iMs-zA-UFJ"/>
<menuItem title="Copy Style" keyEquivalent="c" id="5Vv-lz-BsD">
<modifierMask key="keyEquivalentModifierMask" option="YES" command="YES"/>
<connections>
<action selector="copyFont:" target="Ady-hI-5gd" id="GJO-xA-L4q"/>
</connections>
</menuItem>
<menuItem title="Paste Style" keyEquivalent="v" id="vKC-jM-MkH">
<modifierMask key="keyEquivalentModifierMask" option="YES" command="YES"/>
<connections>
<action selector="pasteFont:" target="Ady-hI-5gd" id="JfD-CL-leO"/>
</connections>
</menuItem>
</items>
</menu>
</menuItem>
<menuItem title="Text" id="Fal-I4-PZk">
<modifierMask key="keyEquivalentModifierMask"/>
<menu key="submenu" title="Text" id="d9c-me-L2H">
<items>
<menuItem title="Align Left" keyEquivalent="{" id="ZM1-6Q-yy1">
<connections>
<action selector="alignLeft:" target="Ady-hI-5gd" id="zUv-R1-uAa"/>
</connections>
</menuItem>
<menuItem title="Center" keyEquivalent="|" id="VIY-Ag-zcb">
<connections>
<action selector="alignCenter:" target="Ady-hI-5gd" id="spX-mk-kcS"/>
</connections>
</menuItem>
<menuItem title="Justify" id="J5U-5w-g23">
<modifierMask key="keyEquivalentModifierMask"/>
<connections>
<action selector="alignJustified:" target="Ady-hI-5gd" id="ljL-7U-jND"/>
</connections>
</menuItem>
<menuItem title="Align Right" keyEquivalent="}" id="wb2-vD-lq4">
<connections>
<action selector="alignRight:" target="Ady-hI-5gd" id="r48-bG-YeY"/>
</connections>
</menuItem>
<menuItem isSeparatorItem="YES" id="4s2-GY-VfK"/>
<menuItem title="Writing Direction" id="H1b-Si-o9J">
<modifierMask key="keyEquivalentModifierMask"/>
<menu key="submenu" title="Writing Direction" id="8mr-sm-Yjd">
<items>
<menuItem title="Paragraph" enabled="NO" id="ZvO-Gk-QUH">
<modifierMask key="keyEquivalentModifierMask"/>
</menuItem>
<menuItem id="YGs-j5-SAR">
<string key="title"> Default</string>
<modifierMask key="keyEquivalentModifierMask"/>
<connections>
<action selector="makeBaseWritingDirectionNatural:" target="Ady-hI-5gd" id="qtV-5e-UBP"/>
</connections>
</menuItem>
<menuItem id="Lbh-J2-qVU">
<string key="title"> Left to Right</string>
<modifierMask key="keyEquivalentModifierMask"/>
<connections>
<action selector="makeBaseWritingDirectionLeftToRight:" target="Ady-hI-5gd" id="S0X-9S-QSf"/>
</connections>
</menuItem>
<menuItem id="jFq-tB-4Kx">
<string key="title"> Right to Left</string>
<modifierMask key="keyEquivalentModifierMask"/>
<connections>
<action selector="makeBaseWritingDirectionRightToLeft:" target="Ady-hI-5gd" id="5fk-qB-AqJ"/>
</connections>
</menuItem>
<menuItem isSeparatorItem="YES" id="swp-gr-a21"/>
<menuItem title="Selection" enabled="NO" id="cqv-fj-IhA">
<modifierMask key="keyEquivalentModifierMask"/>
</menuItem>
<menuItem id="Nop-cj-93Q">
<string key="title"> Default</string>
<modifierMask key="keyEquivalentModifierMask"/>
<connections>
<action selector="makeTextWritingDirectionNatural:" target="Ady-hI-5gd" id="lPI-Se-ZHp"/>
</connections>
</menuItem>
<menuItem id="BgM-ve-c93">
<string key="title"> Left to Right</string>
<modifierMask key="keyEquivalentModifierMask"/>
<connections>
<action selector="makeTextWritingDirectionLeftToRight:" target="Ady-hI-5gd" id="caW-Bv-w94"/>
</connections>
</menuItem>
<menuItem id="RB4-Sm-HuC">
<string key="title"> Right to Left</string>
<modifierMask key="keyEquivalentModifierMask"/>
<connections>
<action selector="makeTextWritingDirectionRightToLeft:" target="Ady-hI-5gd" id="EXD-6r-ZUu"/>
</connections>
</menuItem>
</items>
</menu>
</menuItem>
<menuItem isSeparatorItem="YES" id="fKy-g9-1gm"/>
<menuItem title="Show Ruler" id="vLm-3I-IUL">
<modifierMask key="keyEquivalentModifierMask"/>
<connections>
<action selector="toggleRuler:" target="Ady-hI-5gd" id="FOx-HJ-KwY"/>
</connections>
</menuItem>
<menuItem title="Copy Ruler" keyEquivalent="c" id="MkV-Pr-PK5">
<modifierMask key="keyEquivalentModifierMask" control="YES" command="YES"/>
<connections>
<action selector="copyRuler:" target="Ady-hI-5gd" id="71i-fW-3W2"/>
</connections>
</menuItem>
<menuItem title="Paste Ruler" keyEquivalent="v" id="LVM-kO-fVI">
<modifierMask key="keyEquivalentModifierMask" control="YES" command="YES"/>
<connections>
<action selector="pasteRuler:" target="Ady-hI-5gd" id="cSh-wd-qM2"/>
</connections>
</menuItem>
</items>
</menu>
</menuItem>
</items>
</menu>
</menuItem>
<menuItem title="View" id="H8h-7b-M4v">
<modifierMask key="keyEquivalentModifierMask"/>
<menu key="submenu" title="View" id="HyV-fh-RgO">
<items>
<menuItem title="Show Toolbar" keyEquivalent="t" id="snW-S8-Cw5">
<modifierMask key="keyEquivalentModifierMask" option="YES" command="YES"/>
<connections>
<action selector="toggleToolbarShown:" target="Ady-hI-5gd" id="BXY-wc-z0C"/>
</connections>
</menuItem>
<menuItem title="Customize Toolbar…" id="1UK-8n-QPP">
<modifierMask key="keyEquivalentModifierMask"/>
<connections>
<action selector="runToolbarCustomizationPalette:" target="Ady-hI-5gd" id="pQI-g3-MTW"/>
</connections>
</menuItem>
<menuItem isSeparatorItem="YES" id="hB3-LF-h0Y"/>
<menuItem title="Show Sidebar" keyEquivalent="s" id="kIP-vf-haE">
<modifierMask key="keyEquivalentModifierMask" control="YES" command="YES"/>
<connections>
<action selector="toggleSidebar:" target="Ady-hI-5gd" id="iwa-gc-5KM"/>
</connections>
</menuItem>
<menuItem title="Enter Full Screen" keyEquivalent="f" id="4J7-dP-txa">
<modifierMask key="keyEquivalentModifierMask" control="YES" command="YES"/>
<connections>
<action selector="toggleFullScreen:" target="Ady-hI-5gd" id="dU3-MA-1Rq"/>
</connections>
</menuItem>
</items>
</menu>
</menuItem>
<menuItem title="Window" id="aUF-d1-5bR">
<modifierMask key="keyEquivalentModifierMask"/>
<menu key="submenu" title="Window" systemMenu="window" id="Td7-aD-5lo">
<items>
<menuItem title="Minimize" keyEquivalent="m" id="OY7-WF-poV">
<connections>
<action selector="performMiniaturize:" target="Ady-hI-5gd" id="VwT-WD-YPe"/>
</connections>
</menuItem>
<menuItem title="Zoom" id="R4o-n2-Eq4">
<modifierMask key="keyEquivalentModifierMask"/>
<connections>
<action selector="performZoom:" target="Ady-hI-5gd" id="DIl-cC-cCs"/>
</connections>
</menuItem>
<menuItem isSeparatorItem="YES" id="eu3-7i-yIM"/>
<menuItem title="Bring All to Front" id="LE2-aR-0XJ">
<modifierMask key="keyEquivalentModifierMask"/>
<connections>
<action selector="arrangeInFront:" target="Ady-hI-5gd" id="DRN-fu-gQh"/>
</connections>
</menuItem>
</items>
</menu>
</menuItem>
<menuItem title="Help" id="wpr-3q-Mcd">
<modifierMask key="keyEquivalentModifierMask"/>
<menu key="submenu" title="Help" systemMenu="help" id="F2S-fz-NVQ">
<items>
<menuItem title="SecretiveUpdater Help" keyEquivalent="?" id="FKE-Sm-Kum">
<connections>
<action selector="showHelp:" target="Ady-hI-5gd" id="y7X-2Q-9no"/>
</connections>
</menuItem>
</items>
</menu>
</menuItem>
</items>
</menu>
<connections>
<outlet property="delegate" destination="Voe-Tx-rLC" id="PrD-fu-P6m"/>
</connections>
</application>
<customObject id="Voe-Tx-rLC" customClass="AppDelegate" customModule="SecretiveUpdater" customModuleProvider="target"/>
<customObject id="YLy-65-1bz" customClass="NSFontManager"/>
<customObject id="Ady-hI-5gd" userLabel="First Responder" customClass="NSResponder" sceneMemberID="firstResponder"/>
</objects>
<point key="canvasLocation" x="75" y="0.0"/>
</scene>
</scenes>
</document>

View File

@ -0,0 +1,10 @@
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd">
<plist version="1.0">
<dict>
<key>com.apple.security.application-groups</key>
<array>
<string>$(TeamIdentifierPrefix)com.maxgoedjen.Secretive</string>
</array>
</dict>
</plist>

View File

@ -0,0 +1,110 @@
import Foundation
import Brief
import AppleArchive
import System
import Cocoa
import Security.Authorization
import Security.AuthorizationTags
class Updater: UpdaterProtocol {
func installUpdate(url: URL, to destinationURL: URL) async throws -> String {
// let (downloadedURL, _) = try await URLSession.shared.download(from: url)
// let unzipped = try await decompress(url: downloadedURL)
// try await move(url: unzipped, to: destinationURL)
// let config = NSWorkspace.OpenConfiguration()
// config.activates = true
// TODO: clean
_ = try await authorize()
// if let host = NSRunningApplication.runningApplications(withBundleIdentifier: "com.maxgoedjen.Secretive.Host").first(where: { $0.bundleURL?.path.hasPrefix("/Applications") ?? false }) {
// host.terminate()
//
// }
return "OK"
}
func decompress(url: URL) async throws -> URL {
let zipURL = url.deletingPathExtension().appendingPathExtension("zip")
try FileManager.default.copyItem(at: url, to: zipURL)
let id = UUID()
let destinationURL = FileManager.default.temporaryDirectory.appendingPathComponent("\(id.uuidString)/")
_ = try FileManager.default.createDirectory(at: destinationURL, withIntermediateDirectories: true, attributes: [:])
let process = Process()
let pipe = Pipe()
process.launchPath = "/usr/bin/unzip"
process.arguments = ["-o", zipURL.path, "-d", destinationURL.path]
process.standardOutput = pipe
try process.run()
_ = try pipe.fileHandleForReading.readToEnd()
guard let appURL = try FileManager.default.contentsOfDirectory(at: destinationURL, includingPropertiesForKeys: nil).first(where: { $0.pathExtension == "app" }) else {
throw DecompressionError(reason: "Unzip failed")
}
return appURL
}
func move(url: URL, to destinationURL: URL) async throws {
let auth = try await authorize()
try await move(url: url, to: destinationURL)
try await revokeAuthorization(auth)
}
func authorize() async throws -> AuthorizationRef {
let flags = AuthorizationFlags()
var authorization: AuthorizationRef? = nil
AuthorizationCreate(nil, nil, flags, &authorization)
let authFlags: AuthorizationFlags = [.interactionAllowed, .extendRights, .preAuthorize]
var result: OSStatus?
kAuthorizationRightExecute.withCString { cString in
var item = AuthorizationItem(name: cString, valueLength: 0, value: nil, flags: 0)
withUnsafeMutablePointer(to: &item) { pointer in
var rights = AuthorizationRights(count: 1, items: pointer)
result = AuthorizationCopyRights(authorization!, &rights, nil, authFlags, nil)
}
}
guard result == errAuthorizationSuccess, let authorization = authorization else {
throw RightsNotAcquiredError()
}
return authorization
}
func revokeAuthorization(_ authorization: AuthorizationRef) async throws {
AuthorizationFree(authorization, .destroyRights)
}
func priveledgedMove(url: URL, to destination: URL) async throws {
try FileManager.default.replaceItemAt(destination, withItemAt: url)
}
}
extension Updater {
struct DecompressionError: Error, LocalizedError {
let reason: String
}
struct RightsNotAcquiredError: Error, LocalizedError {
}
}
extension URLSession {
@available(macOS, deprecated: 12.0)
public func download(from url: URL) async throws -> (URL, URLResponse) {
try await withCheckedThrowingContinuation { continuation in
let task = downloadTask(with: url) { url, response, error in
guard let url = url, let response = response else {
continuation.resume(throwing: error ?? UnknownError())
return
}
continuation.resume(returning: (url, response))
}
task.resume()
}
}
struct UnknownError: Error {}
}

View File

@ -0,0 +1,8 @@
import Foundation
import Brief
@objc public protocol UpdaterProtocol {
func installUpdate(url: URL, to: URL) async throws -> String
}

View File

@ -0,0 +1,26 @@
import Foundation
class ServiceDelegate: NSObject, NSXPCListenerDelegate {
let exported: UpdaterProtocol
init(exportedObject: UpdaterProtocol) {
self.exported = exportedObject
}
func listener(_ listener: NSXPCListener, shouldAcceptNewConnection newConnection: NSXPCConnection) -> Bool {
newConnection.exportedInterface = NSXPCInterface(with: UpdaterProtocol.self)
newConnection.exportedObject = exported
newConnection.resume()
return true
}
}
let updater = Updater()
let delegate = ServiceDelegate(exportedObject: Updater())
let listener = NSXPCListener(machServiceName: Bundle.main.bundleIdentifier!)
listener.delegate = delegate
listener.resume()
try "Hello world".data(using: .utf8)?.write(to: URL(fileURLWithPath: "/Users/max/Downloads/\(UUID().uuidString).txt"))
RunLoop.current.run()