mirror of
https://github.com/maxgoedjen/secretive.git
synced 2025-07-01 09:43:37 +00:00
Compare commits
75 Commits
proxystore
...
swift6
Author | SHA1 | Date | |
---|---|---|---|
bab76da2ab | |||
9b02afb20c | |||
576e625b8f | |||
304741e019 | |||
8e707545d1 | |||
e332b7cb9d | |||
c09ad3ecc1 | |||
28a4dafad4 | |||
c2563be404 | |||
970e407e29 | |||
2dc317d398 | |||
8ea8f0510c | |||
ad56019901 | |||
5929137f20 | |||
35a7c99cba | |||
a543de0737 | |||
fc21018eb4 | |||
52cc08424e | |||
d13f4ee7ba | |||
6f4226f97a | |||
3315a4bfbc | |||
85a7a64bc9 | |||
409efa5f9f | |||
bb63ae8469 | |||
30c1d36974 | |||
de8d18f9e9 | |||
1ae0996e2c | |||
3d50a99430 | |||
45fc356f0f | |||
212678b94e | |||
2e1f4881a9 | |||
c2b80e3c7c | |||
15d2afd2cb | |||
2a4da36c4e | |||
1fc8fa25d9 | |||
5718ae6805 | |||
5af84583ab | |||
afc54c5e40 | |||
c80a6f1b0b | |||
8c67ea7c73 | |||
171981de9f | |||
cf58630065 | |||
7b0ccbcc16 | |||
dbaa57a05a | |||
6248ecc9db | |||
d82bb80e14 | |||
5bf5be6c25 | |||
1d4ef12546 | |||
df10fa3912 | |||
e04fe419ed | |||
0944d65ccb | |||
2ca8279187 | |||
be58ddd324 | |||
93e79470b7 | |||
43a9e287c3 | |||
f54b2a33bf | |||
3bd8e3b494 | |||
14b351abee | |||
480ef5392d | |||
8679ca3da0 | |||
f43571baa3 | |||
acdf0baf3a | |||
1a362ef955 | |||
3b254d33a5 | |||
382913cb99 | |||
20cbaac6f6 | |||
47d736cb0d | |||
fa0e81cd8e | |||
e31db0f4fa | |||
403709ac83 | |||
5f055efa18 | |||
e77812c06c | |||
8744313ba1 | |||
26d6ced9ee | |||
71b4780488 |
BIN
.github/readme/app-dark.png
vendored
Normal file
BIN
.github/readme/app-dark.png
vendored
Normal file
Binary file not shown.
After Width: | Height: | Size: 572 KiB |
BIN
.github/readme/app-light.png
vendored
Normal file
BIN
.github/readme/app-light.png
vendored
Normal file
Binary file not shown.
After Width: | Height: | Size: 545 KiB |
BIN
.github/readme/app.png
vendored
BIN
.github/readme/app.png
vendored
Binary file not shown.
Before Width: | Height: | Size: 580 KiB |
BIN
.github/readme/localize_add.png
vendored
Normal file
BIN
.github/readme/localize_add.png
vendored
Normal file
Binary file not shown.
After Width: | Height: | Size: 1.3 MiB |
BIN
.github/readme/localize_sidebar.png
vendored
Normal file
BIN
.github/readme/localize_sidebar.png
vendored
Normal file
Binary file not shown.
After Width: | Height: | Size: 162 KiB |
BIN
.github/readme/localize_translate.png
vendored
Normal file
BIN
.github/readme/localize_translate.png
vendored
Normal file
Binary file not shown.
After Width: | Height: | Size: 1.7 MiB |
16
.github/workflows/add-to-project.yml
vendored
Normal file
16
.github/workflows/add-to-project.yml
vendored
Normal file
@ -0,0 +1,16 @@
|
||||
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 }}
|
15
.github/workflows/nightly.yml
vendored
15
.github/workflows/nightly.yml
vendored
@ -5,10 +5,11 @@ on:
|
||||
- cron: "0 8 * * *"
|
||||
jobs:
|
||||
build:
|
||||
runs-on: macos-11.0
|
||||
# runs-on: macOS-latest
|
||||
runs-on: macos-15
|
||||
timeout-minutes: 10
|
||||
steps:
|
||||
- uses: actions/checkout@v2
|
||||
- uses: actions/checkout@v4
|
||||
- name: Setup Signing
|
||||
env:
|
||||
SIGNING_DATA: ${{ secrets.SIGNING_DATA }}
|
||||
@ -19,7 +20,7 @@ jobs:
|
||||
APPLE_API_KEY_ID: ${{ secrets.APPLE_API_KEY_ID }}
|
||||
run: ./.github/scripts/signing.sh
|
||||
- name: Set Environment
|
||||
run: sudo xcrun xcode-select -s /Applications/Xcode_13.2.1.app
|
||||
run: sudo xcrun xcode-select -s /Applications/Xcode_16.2.app
|
||||
- name: Update Build Number
|
||||
env:
|
||||
RUN_ID: ${{ github.run_id }}
|
||||
@ -40,10 +41,14 @@ 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
|
||||
- name: Document SHAs
|
||||
run: |
|
||||
echo "sha-512:"
|
||||
shasum -a 512 Secretive.zip
|
||||
shasum -a 512 Archive.zip
|
||||
echo "sha-256:"
|
||||
shasum -a 256 Secretive.zip
|
||||
shasum -a 256 Archive.zip
|
||||
- name: Upload App to Artifacts
|
||||
uses: actions/upload-artifact@v1
|
||||
uses: actions/upload-artifact@v4
|
||||
with:
|
||||
name: Secretive.zip
|
||||
path: Secretive.zip
|
||||
path: Secretive.zip
|
||||
|
22
.github/workflows/release.yml
vendored
22
.github/workflows/release.yml
vendored
@ -6,10 +6,11 @@ on:
|
||||
- '*'
|
||||
jobs:
|
||||
test:
|
||||
runs-on: macos-11.0
|
||||
# runs-on: macOS-latest
|
||||
runs-on: macos-15
|
||||
timeout-minutes: 10
|
||||
steps:
|
||||
- uses: actions/checkout@v1
|
||||
- uses: actions/checkout@v4
|
||||
- name: Setup Signing
|
||||
env:
|
||||
SIGNING_DATA: ${{ secrets.SIGNING_DATA }}
|
||||
@ -20,17 +21,18 @@ jobs:
|
||||
APPLE_API_KEY_ID: ${{ secrets.APPLE_API_KEY_ID }}
|
||||
run: ./.github/scripts/signing.sh
|
||||
- name: Set Environment
|
||||
run: sudo xcrun xcode-select -s /Applications/Xcode_13.2.1.app
|
||||
run: sudo xcrun xcode-select -s /Applications/Xcode_16.2.app
|
||||
- name: Test
|
||||
run: |
|
||||
pushd Sources/Packages
|
||||
swift test
|
||||
popd
|
||||
build:
|
||||
runs-on: macos-11.0
|
||||
# runs-on: macOS-latest
|
||||
runs-on: macos-15
|
||||
timeout-minutes: 10
|
||||
steps:
|
||||
- uses: actions/checkout@v2
|
||||
- uses: actions/checkout@v4
|
||||
- name: Setup Signing
|
||||
env:
|
||||
SIGNING_DATA: ${{ secrets.SIGNING_DATA }}
|
||||
@ -41,7 +43,7 @@ jobs:
|
||||
APPLE_API_KEY_ID: ${{ secrets.APPLE_API_KEY_ID }}
|
||||
run: ./.github/scripts/signing.sh
|
||||
- name: Set Environment
|
||||
run: sudo xcrun xcode-select -s /Applications/Xcode_13.2.1.app
|
||||
run: sudo xcrun xcode-select -s /Applications/Xcode_16.2.app
|
||||
- name: Update Build Number
|
||||
env:
|
||||
TAG_NAME: ${{ github.ref }}
|
||||
@ -64,8 +66,12 @@ 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
|
||||
- name: Document SHAs
|
||||
run: |
|
||||
echo "sha-512:"
|
||||
shasum -a 512 Secretive.zip
|
||||
shasum -a 512 Archive.zip
|
||||
echo "sha-256:"
|
||||
shasum -a 256 Secretive.zip
|
||||
shasum -a 256 Archive.zip
|
||||
- name: Create Release
|
||||
id: create_release
|
||||
uses: actions/create-release@v1
|
||||
@ -101,12 +107,12 @@ jobs:
|
||||
asset_name: Secretive.zip
|
||||
asset_content_type: application/zip
|
||||
- name: Upload App to Artifacts
|
||||
uses: actions/upload-artifact@v1
|
||||
uses: actions/upload-artifact@v4
|
||||
with:
|
||||
name: Secretive.zip
|
||||
path: Secretive.zip
|
||||
- name: Upload Archive to Artifacts
|
||||
uses: actions/upload-artifact@v1
|
||||
uses: actions/upload-artifact@v4
|
||||
with:
|
||||
name: Xcode_Archive.zip
|
||||
path: Archive.zip
|
||||
|
7
.github/workflows/test.yml
vendored
7
.github/workflows/test.yml
vendored
@ -3,12 +3,13 @@ name: Test
|
||||
on: [push, pull_request]
|
||||
jobs:
|
||||
test:
|
||||
runs-on: macos-11.0
|
||||
# runs-on: macOS-latest
|
||||
runs-on: macos-15
|
||||
timeout-minutes: 10
|
||||
steps:
|
||||
- uses: actions/checkout@v2
|
||||
- uses: actions/checkout@v4
|
||||
- name: Set Environment
|
||||
run: sudo xcrun xcode-select -s /Applications/Xcode_13.2.1.app
|
||||
run: sudo xcrun xcode-select -s /Applications/Xcode_16.2.app
|
||||
- name: Test
|
||||
run: |
|
||||
pushd Sources/Packages
|
||||
|
@ -26,6 +26,15 @@ Host *
|
||||
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
|
||||
|
||||
Add this to `~/Library/LaunchAgents/com.maxgoedjen.Secretive.SecretAgent.plist`
|
||||
@ -51,6 +60,31 @@ Add this to `~/Library/LaunchAgents/com.maxgoedjen.Secretive.SecretAgent.plist`
|
||||
|
||||
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
|
||||
|
||||
Add this to `~/Library/LaunchAgents/com.maxgoedjen.Secretive.SecretAgent.plist`
|
||||
|
@ -14,6 +14,10 @@ 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)
|
||||
|
||||
## Localization
|
||||
|
||||
If you'd like to contribute a translation, please see [Localizing](LOCALIZING.md) to get started.
|
||||
|
||||
## 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).
|
||||
|
8
FAQ.md
8
FAQ.md
@ -12,6 +12,10 @@ 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.
|
||||
|
||||
### 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
|
||||
|
||||
1) Make sure you have enabled "Use your Apple Watch to unlock apps and your Mac" in System Preferences --> Security & Privacy:
|
||||
@ -28,6 +32,10 @@ Please run `ssh -Tv git@github.com` in your terminal and paste the output in a [
|
||||
|
||||
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.
|
||||
|
||||
### 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.
|
||||
|
37
LOCALIZING.md
Normal file
37
LOCALIZING.md
Normal file
@ -0,0 +1,37 @@
|
||||
# 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!
|
@ -3,7 +3,10 @@
|
||||
|
||||
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.
|
||||
|
||||
<img src="/.github/readme/app.png" alt="Screenshot of Secretive" width="600">
|
||||
<picture>
|
||||
<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?
|
||||
@ -14,7 +17,7 @@ The most common setup for SSH keys is just keeping them on disk, guarded by prop
|
||||
|
||||
### 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 key 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 keys 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">
|
||||
|
||||
|
@ -1,4 +1,4 @@
|
||||
// swift-tools-version:5.5
|
||||
// swift-tools-version:6.0
|
||||
// The swift-tools-version declares the minimum version of Swift required to build this package.
|
||||
|
||||
import PackageDescription
|
||||
@ -6,7 +6,7 @@ import PackageDescription
|
||||
let package = Package(
|
||||
name: "SecretivePackages",
|
||||
platforms: [
|
||||
.macOS(.v11)
|
||||
.macOS(.v15)
|
||||
],
|
||||
products: [
|
||||
.library(
|
||||
@ -33,23 +33,28 @@ let package = Package(
|
||||
targets: [
|
||||
.target(
|
||||
name: "SecretKit",
|
||||
dependencies: []
|
||||
dependencies: [],
|
||||
swiftSettings: swiftSettings
|
||||
),
|
||||
.testTarget(
|
||||
name: "SecretKitTests",
|
||||
dependencies: ["SecretKit", "SecureEnclaveSecretKit", "SmartCardSecretKit"]
|
||||
dependencies: ["SecretKit", "SecureEnclaveSecretKit", "SmartCardSecretKit"],
|
||||
swiftSettings: swiftSettings
|
||||
),
|
||||
.target(
|
||||
name: "SecureEnclaveSecretKit",
|
||||
dependencies: ["SecretKit"]
|
||||
dependencies: ["SecretKit"],
|
||||
swiftSettings: swiftSettings
|
||||
),
|
||||
.target(
|
||||
name: "SmartCardSecretKit",
|
||||
dependencies: ["SecretKit"]
|
||||
dependencies: ["SecretKit"],
|
||||
swiftSettings: swiftSettings
|
||||
),
|
||||
.target(
|
||||
name: "SecretAgentKit",
|
||||
dependencies: ["SecretKit", "SecretAgentKitHeaders"]
|
||||
dependencies: ["SecretKit", "SecretAgentKitHeaders"],
|
||||
swiftSettings: swiftSettings
|
||||
),
|
||||
.systemLibrary(
|
||||
name: "SecretAgentKitHeaders"
|
||||
@ -68,3 +73,10 @@ let package = Package(
|
||||
),
|
||||
]
|
||||
)
|
||||
|
||||
var swiftSettings: [PackageDescription.SwiftSetting] {
|
||||
[
|
||||
.swiftLanguageMode(.v6),
|
||||
.unsafeFlags(["-warnings-as-errors"])
|
||||
]
|
||||
}
|
||||
|
@ -1,7 +1,7 @@
|
||||
import Foundation
|
||||
|
||||
/// A release is a representation of a downloadable update.
|
||||
public struct Release: Codable {
|
||||
public struct Release: Codable, Sendable {
|
||||
|
||||
/// The user-facing name of the release. Typically "Secretive 1.2.3"
|
||||
public let name: String
|
||||
|
@ -1,7 +1,7 @@
|
||||
import Foundation
|
||||
|
||||
/// A representation of a Semantic Version.
|
||||
public struct SemVer {
|
||||
public struct SemVer: Sendable {
|
||||
|
||||
/// The SemVer broken into an array of integers.
|
||||
let versionNumbers: [Int]
|
||||
|
@ -1,10 +1,14 @@
|
||||
import Foundation
|
||||
import Combine
|
||||
import Observation
|
||||
import Synchronization
|
||||
|
||||
/// A concrete implementation of ``UpdaterProtocol`` which considers the current release and OS version.
|
||||
public class Updater: ObservableObject, UpdaterProtocol {
|
||||
@Observable public final class Updater: UpdaterProtocol, ObservableObject, Sendable {
|
||||
|
||||
@Published public var update: Release?
|
||||
public var update: Release? {
|
||||
_update.withLock { $0 }
|
||||
}
|
||||
private let _update: Mutex<Release?> = .init(nil)
|
||||
public let testBuild: Bool
|
||||
|
||||
/// The current OS version.
|
||||
@ -24,30 +28,34 @@ public class Updater: ObservableObject, UpdaterProtocol {
|
||||
testBuild = currentVersion == SemVer("0.0.0")
|
||||
if checkOnLaunch {
|
||||
// Don't do a launch check if the user hasn't seen the setup prompt explaining updater yet.
|
||||
checkForUpdates()
|
||||
Task {
|
||||
await checkForUpdates()
|
||||
}
|
||||
}
|
||||
let timer = Timer.scheduledTimer(withTimeInterval: checkFrequency, repeats: true) { _ in
|
||||
self.checkForUpdates()
|
||||
Task {
|
||||
while !Task.isCancelled {
|
||||
try? await Task.sleep(for: .seconds(Int(checkFrequency)))
|
||||
await checkForUpdates()
|
||||
}
|
||||
}
|
||||
timer.tolerance = 60*60
|
||||
}
|
||||
|
||||
/// Manually trigger an update check.
|
||||
public func checkForUpdates() {
|
||||
URLSession.shared.dataTask(with: Constants.updateURL) { data, _, _ in
|
||||
guard let data = data else { return }
|
||||
guard let releases = try? JSONDecoder().decode([Release].self, from: data) else { return }
|
||||
self.evaluate(releases: releases)
|
||||
}.resume()
|
||||
public func checkForUpdates() async {
|
||||
guard let (data, _) = try? await URLSession.shared.data(from: Constants.updateURL) else { return }
|
||||
guard let releases = try? JSONDecoder().decode([Release].self, from: data) else { return }
|
||||
await evaluate(releases: releases)
|
||||
}
|
||||
|
||||
/// Ignores a specified release. `update` will be nil if the user has ignored the latest available release.
|
||||
/// - Parameter release: The release to ignore.
|
||||
public func ignore(release: Release) {
|
||||
public func ignore(release: Release) async {
|
||||
guard !release.critical else { return }
|
||||
defaults.set(true, forKey: release.name)
|
||||
DispatchQueue.main.async {
|
||||
self.update = nil
|
||||
await MainActor.run {
|
||||
_update.withLock { value in
|
||||
value = nil
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@ -57,7 +65,7 @@ extension Updater {
|
||||
|
||||
/// 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.
|
||||
func evaluate(releases: [Release]) {
|
||||
func evaluate(releases: [Release]) async {
|
||||
guard let release = releases
|
||||
.sorted()
|
||||
.reversed()
|
||||
@ -67,8 +75,10 @@ extension Updater {
|
||||
guard !release.prerelease else { return }
|
||||
let latestVersion = SemVer(release.name)
|
||||
if latestVersion > currentVersion {
|
||||
DispatchQueue.main.async {
|
||||
self.update = release
|
||||
await MainActor.run {
|
||||
_update.withLock { value in
|
||||
value = release
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
@ -1,7 +1,8 @@
|
||||
import Foundation
|
||||
import Synchronization
|
||||
|
||||
/// A protocol for retreiving the latest available version of an app.
|
||||
public protocol UpdaterProtocol: ObservableObject {
|
||||
public protocol UpdaterProtocol: Observable {
|
||||
|
||||
/// The latest update
|
||||
var update: Release? { get }
|
||||
|
@ -5,21 +5,24 @@ import SecretKit
|
||||
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.
|
||||
public class Agent {
|
||||
public final class Agent: Sendable {
|
||||
|
||||
private let storeList: SecretStoreList
|
||||
private let witness: SigningWitness?
|
||||
private let writer = OpenSSHKeyWriter()
|
||||
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.
|
||||
/// - Parameters:
|
||||
/// - storeList: The `SecretStoreList` to make available.
|
||||
/// - witness: A witness to notify of requests.
|
||||
public init(storeList: SecretStoreList, witness: SigningWitness? = nil) {
|
||||
Logger().debug("Agent is running")
|
||||
logger.debug("Agent is running")
|
||||
self.storeList = storeList
|
||||
self.witness = witness
|
||||
certificateHandler.reloadCertificates(for: storeList.allSecrets)
|
||||
}
|
||||
|
||||
}
|
||||
@ -32,41 +35,43 @@ extension Agent {
|
||||
/// - writer: A ``FileHandleWriter`` to write the response to.
|
||||
/// - Return value:
|
||||
/// - Boolean if data could be read
|
||||
@discardableResult public func handle(reader: FileHandleReader, writer: FileHandleWriter) -> Bool {
|
||||
Logger().debug("Agent handling new data")
|
||||
@discardableResult public func handle(reader: FileHandleReader, writer: FileHandleWriter) async -> Bool {
|
||||
logger.debug("Agent handling new data")
|
||||
let data = Data(reader.availableData)
|
||||
guard data.count > 4 else { return false}
|
||||
let requestTypeInt = data[4]
|
||||
guard let requestType = SSHAgent.RequestType(rawValue: requestTypeInt) else {
|
||||
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
|
||||
}
|
||||
Logger().debug("Agent handling request of type \(requestType.debugDescription)")
|
||||
logger.debug("Agent handling request of type \(requestType.debugDescription)")
|
||||
let subData = Data(data[5...])
|
||||
let response = handle(requestType: requestType, data: subData, reader: reader)
|
||||
let response = await handle(requestType: requestType, data: subData, reader: reader)
|
||||
writer.write(response)
|
||||
return true
|
||||
}
|
||||
|
||||
func handle(requestType: SSHAgent.RequestType, data: Data, reader: FileHandleReader) -> Data {
|
||||
func handle(requestType: SSHAgent.RequestType, data: Data, reader: FileHandleReader) async -> 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()
|
||||
do {
|
||||
switch requestType {
|
||||
case .requestIdentities:
|
||||
response.append(SSHAgent.ResponseType.agentIdentitiesAnswer.data)
|
||||
response.append(identities())
|
||||
Logger().debug("Agent returned \(SSHAgent.ResponseType.agentIdentitiesAnswer.debugDescription)")
|
||||
logger.debug("Agent returned \(SSHAgent.ResponseType.agentIdentitiesAnswer.debugDescription)")
|
||||
case .signRequest:
|
||||
let provenance = requestTracer.provenance(from: reader)
|
||||
response.append(SSHAgent.ResponseType.agentSignResponse.data)
|
||||
response.append(try sign(data: data, provenance: provenance))
|
||||
Logger().debug("Agent returned \(SSHAgent.ResponseType.agentSignResponse.debugDescription)")
|
||||
response.append(try await sign(data: data, provenance: provenance))
|
||||
logger.debug("Agent returned \(SSHAgent.ResponseType.agentSignResponse.debugDescription)")
|
||||
}
|
||||
} catch {
|
||||
response.removeAll()
|
||||
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)
|
||||
return full
|
||||
@ -79,18 +84,26 @@ extension Agent {
|
||||
/// Lists the identities available for signing operations
|
||||
/// - Returns: An OpenSSH formatted Data payload listing the identities available for signing operations.
|
||||
func identities() -> Data {
|
||||
let secrets = storeList.stores.flatMap(\.secrets)
|
||||
var count = UInt32(secrets.count).bigEndian
|
||||
let countData = Data(bytes: &count, count: UInt32.bitWidth/8)
|
||||
let secrets = storeList.allSecrets
|
||||
certificateHandler.reloadCertificates(for: secrets)
|
||||
var count = secrets.count
|
||||
var keyData = Data()
|
||||
let writer = OpenSSHKeyWriter()
|
||||
|
||||
for secret in secrets {
|
||||
let keyBlob = writer.data(secret: secret)
|
||||
keyData.append(writer.lengthAndData(of: keyBlob))
|
||||
let curveData = writer.curveType(for: secret.algorithm, length: secret.keySize).data(using: .utf8)!
|
||||
keyData.append(writer.lengthAndData(of: keyBlob))
|
||||
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().debug("Agent enumerated \(secrets.count) identities")
|
||||
logger.log("Agent enumerated \(count) identities")
|
||||
var countBigEndian = UInt32(count).bigEndian
|
||||
let countData = Data(bytes: &countBigEndian, count: UInt32.bitWidth/8)
|
||||
return countData + keyData
|
||||
}
|
||||
|
||||
@ -99,20 +112,28 @@ extension Agent {
|
||||
/// - data: The data to sign.
|
||||
/// - provenance: A ``SecretKit.SigningRequestProvenance`` object describing the origin of the request.
|
||||
/// - Returns: An OpenSSH formatted Data payload containing the signed data response.
|
||||
func sign(data: Data, provenance: SigningRequestProvenance) throws -> Data {
|
||||
func sign(data: Data, provenance: SigningRequestProvenance) async throws -> Data {
|
||||
let reader = OpenSSHReader(data: data)
|
||||
let hash = reader.readNextChunk()
|
||||
let payloadHash = 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 {
|
||||
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
|
||||
}
|
||||
|
||||
if let witness = witness {
|
||||
try witness.speakNowOrForeverHoldYourPeace(forAccessTo: secret, from: store, by: provenance)
|
||||
try await witness.speakNowOrForeverHoldYourPeace(forAccessTo: secret, from: store, by: provenance)
|
||||
}
|
||||
|
||||
let dataToSign = reader.readNextChunk()
|
||||
let signed = try store.sign(data: dataToSign, with: secret, for: provenance)
|
||||
let signed = try await store.sign(data: dataToSign, with: secret, for: provenance)
|
||||
let derSignature = signed
|
||||
|
||||
let curveData = writer.curveType(for: secret.algorithm, length: secret.keySize).data(using: .utf8)!
|
||||
@ -154,10 +175,10 @@ extension Agent {
|
||||
signedData.append(writer.lengthAndData(of: sub))
|
||||
|
||||
if let witness = witness {
|
||||
try witness.witness(accessTo: secret, from: store, by: provenance)
|
||||
try await witness.witness(accessTo: secret, from: store, by: provenance)
|
||||
}
|
||||
|
||||
Logger().debug("Agent signed request")
|
||||
logger.debug("Agent signed request")
|
||||
|
||||
return signedData
|
||||
}
|
||||
@ -166,6 +187,16 @@ 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.
|
||||
/// - Parameter hash: The hash to match against.
|
||||
/// - Returns: A ``Secret`` and the ``SecretStore`` containing it, if a match is found.
|
||||
@ -191,6 +222,7 @@ extension Agent {
|
||||
case unhandledType
|
||||
case noMatchingKey
|
||||
case unsupportedKeyType
|
||||
case notOpenSSHCertificate
|
||||
}
|
||||
|
||||
}
|
||||
|
@ -1,7 +1,7 @@
|
||||
import Foundation
|
||||
|
||||
/// Protocol abstraction of the reading aspects of FileHandle.
|
||||
public protocol FileHandleReader {
|
||||
public protocol FileHandleReader: Sendable {
|
||||
|
||||
/// Gets data that is available for reading.
|
||||
var availableData: Data { get }
|
||||
@ -13,7 +13,7 @@ public protocol FileHandleReader {
|
||||
}
|
||||
|
||||
/// Protocol abstraction of the writing aspects of FileHandle.
|
||||
public protocol FileHandleWriter {
|
||||
public protocol FileHandleWriter: Sendable {
|
||||
|
||||
/// Writes data to the handle.
|
||||
func write(_ data: Data)
|
||||
|
@ -1,11 +1,11 @@
|
||||
import Foundation
|
||||
|
||||
/// A namespace for the SSH Agent Protocol, as described in https://tools.ietf.org/id/draft-miller-ssh-agent-01.html
|
||||
/// A namespace for the SSH Agent Protocol, as described in https://datatracker.ietf.org/doc/html/draft-miller-ssh-agent#section-5.1
|
||||
public enum SSHAgent {}
|
||||
|
||||
extension SSHAgent {
|
||||
|
||||
/// 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
|
||||
/// The type of the SSH Agent Request, as described in https://datatracker.ietf.org/doc/html/draft-miller-ssh-agent#section-5.1
|
||||
public enum RequestType: UInt8, CustomDebugStringConvertible {
|
||||
|
||||
case requestIdentities = 11
|
||||
@ -21,10 +21,11 @@ extension SSHAgent {
|
||||
}
|
||||
}
|
||||
|
||||
/// 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
|
||||
/// The type of the SSH Agent Response, as described in https://datatracker.ietf.org/doc/html/draft-miller-ssh-agent#section-5.1
|
||||
public enum ResponseType: UInt8, CustomDebugStringConvertible {
|
||||
|
||||
case agentFailure = 5
|
||||
case agentSuccess = 6
|
||||
case agentIdentitiesAnswer = 12
|
||||
case agentSignResponse = 14
|
||||
|
||||
@ -32,6 +33,8 @@ extension SSHAgent {
|
||||
switch self {
|
||||
case .agentFailure:
|
||||
return "AgentFailure"
|
||||
case .agentSuccess:
|
||||
return "AgentSuccess"
|
||||
case .agentIdentitiesAnswer:
|
||||
return "AgentIdentitiesAnswer"
|
||||
case .agentSignResponse:
|
||||
|
11
Sources/Packages/Sources/SecretAgentKit/Sendability.swift
Normal file
11
Sources/Packages/Sources/SecretAgentKit/Sendability.swift
Normal file
@ -0,0 +1,11 @@
|
||||
import Foundation
|
||||
|
||||
struct UncheckedSendable<T>: @unchecked Sendable {
|
||||
|
||||
let value: T
|
||||
|
||||
init(_ value: T) {
|
||||
self.value = value
|
||||
}
|
||||
|
||||
}
|
@ -40,7 +40,10 @@ extension SigningRequestTracer {
|
||||
func process(from pid: Int32) -> SigningRequestProvenance.Process {
|
||||
var pidAndNameInfo = self.pidAndNameInfo(from: pid)
|
||||
let ppid = pidAndNameInfo.kp_eproc.e_ppid != 0 ? pidAndNameInfo.kp_eproc.e_ppid : nil
|
||||
let procName = String(cString: &pidAndNameInfo.kp_proc.p_comm.0)
|
||||
let procName = withUnsafeMutablePointer(to: &pidAndNameInfo.kp_proc.p_comm.0) { pointer in
|
||||
String(cString: pointer)
|
||||
}
|
||||
|
||||
let pathPointer = UnsafeMutablePointer<UInt8>.allocate(capacity: Int(MAXPATHLEN))
|
||||
_ = proc_pidpath(pid, pathPointer, UInt32(MAXPATHLEN))
|
||||
let path = String(cString: pathPointer)
|
||||
@ -57,7 +60,10 @@ extension SigningRequestTracer {
|
||||
func iconURL(for pid: Int32) -> URL? {
|
||||
do {
|
||||
if let app = NSRunningApplication(processIdentifier: pid), let icon = app.icon?.tiffRepresentation {
|
||||
let temporaryURL = URL(fileURLWithPath: (NSTemporaryDirectory() as NSString).appendingPathComponent("\(UUID().uuidString).png"))
|
||||
let temporaryURL = URL(fileURLWithPath: (NSTemporaryDirectory() as NSString).appendingPathComponent("\(app.bundleIdentifier ?? UUID().uuidString).png"))
|
||||
if FileManager.default.fileExists(atPath: temporaryURL.path) {
|
||||
return temporaryURL
|
||||
}
|
||||
let bitmap = NSBitmapImageRep(data: icon)
|
||||
try bitmap?.representation(using: .png, properties: [:])?.write(to: temporaryURL)
|
||||
return temporaryURL
|
||||
|
@ -2,7 +2,7 @@ import Foundation
|
||||
import SecretKit
|
||||
|
||||
/// A protocol that allows conformers to be notified of access to secrets, and optionally prevent access.
|
||||
public protocol SigningWitness {
|
||||
public protocol SigningWitness: Sendable {
|
||||
|
||||
/// 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:
|
||||
@ -10,13 +10,13 @@ public protocol SigningWitness {
|
||||
/// - store: The `Store` being asked to sign 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.
|
||||
func speakNowOrForeverHoldYourPeace(forAccessTo secret: AnySecret, from store: AnySecretStore, by provenance: SigningRequestProvenance) throws
|
||||
func speakNowOrForeverHoldYourPeace(forAccessTo secret: AnySecret, from store: AnySecretStore, by provenance: SigningRequestProvenance) async throws
|
||||
|
||||
/// Notifies the callee that a signing operation has been performed for a given secret.
|
||||
/// - Parameters:
|
||||
/// - secret: The `Secret` that will was used to sign the request.
|
||||
/// - store: The `Store` that signed the request..
|
||||
/// - provenance: A `SigningRequestProvenance` object describing the origin of the request.
|
||||
func witness(accessTo secret: AnySecret, from store: AnySecretStore, by provenance: SigningRequestProvenance) throws
|
||||
func witness(accessTo secret: AnySecret, from store: AnySecretStore, by provenance: SigningRequestProvenance) async throws
|
||||
|
||||
}
|
||||
|
@ -2,7 +2,7 @@ import Foundation
|
||||
import OSLog
|
||||
|
||||
/// A controller that manages socket configuration and request dispatching.
|
||||
public class SocketController {
|
||||
public final class SocketController {
|
||||
|
||||
/// The active FileHandle.
|
||||
private var fileHandle: FileHandle?
|
||||
@ -10,22 +10,24 @@ public class SocketController {
|
||||
private var port: SocketPort?
|
||||
/// A handler that will be notified when a new read/write handle is available.
|
||||
/// False if no data could be read
|
||||
public var handler: ((FileHandleReader, FileHandleWriter) -> Bool)?
|
||||
public var handler: (@Sendable (FileHandleReader, FileHandleWriter) async -> Bool)?
|
||||
/// Logger.
|
||||
private let logger = Logger(subsystem: "com.maxgoedjen.secretive.secretagent", category: "SocketController")
|
||||
|
||||
|
||||
/// Initializes a socket controller with a specified path.
|
||||
/// - Parameter path: The path to use as a socket.
|
||||
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) {
|
||||
Logger().debug("Socket controller removed existing socket")
|
||||
logger.debug("Socket controller removed existing socket")
|
||||
}
|
||||
let exists = FileManager.default.fileExists(atPath: path)
|
||||
assert(!exists)
|
||||
Logger().debug("Socket controller path is clear")
|
||||
logger.debug("Socket controller path is clear")
|
||||
port = socketPort(at: path)
|
||||
configureSocket(at: path)
|
||||
Logger().debug("Socket listening at \(path)")
|
||||
logger.debug("Socket listening at \(path)")
|
||||
}
|
||||
|
||||
/// Configures the socket and a corresponding FileHandle.
|
||||
@ -35,7 +37,7 @@ public class SocketController {
|
||||
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(handleConnectionDataAvailable(notification:)), name: .NSFileHandleDataAvailable, object: nil)
|
||||
fileHandle?.acceptConnectionInBackgroundAndNotify(forModes: [RunLoop.current.currentMode!])
|
||||
fileHandle?.acceptConnectionInBackgroundAndNotify(forModes: [RunLoop.Mode.common])
|
||||
}
|
||||
|
||||
/// Creates a SocketPort for a path.
|
||||
@ -65,25 +67,45 @@ public class SocketController {
|
||||
/// Handles a new connection being accepted, invokes the handler, and prepares to accept new connections.
|
||||
/// - Parameter notification: A `Notification` that triggered the call.
|
||||
@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 }
|
||||
_ = handler?(new, new)
|
||||
new.waitForDataInBackgroundAndNotify()
|
||||
fileHandle?.acceptConnectionInBackgroundAndNotify(forModes: [RunLoop.current.currentMode!])
|
||||
Task { [handler, fileHandle] in
|
||||
_ = await handler?(new, new)
|
||||
await new.waitForDataInBackgroundAndNotifyOnMainActor()
|
||||
await fileHandle?.acceptConnectionInBackgroundAndNotifyOnMainActor()
|
||||
}
|
||||
}
|
||||
|
||||
/// Handles a new connection providing data and invokes the handler callback.
|
||||
/// - Parameter notification: A `Notification` that triggered the call.
|
||||
@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 }
|
||||
Logger().debug("Socket controller received new file handle")
|
||||
if((handler?(new, new)) == true) {
|
||||
Logger().debug("Socket controller handled data, wait for more data")
|
||||
new.waitForDataInBackgroundAndNotify()
|
||||
} else {
|
||||
Logger().debug("Socket controller called with empty data, socked closed")
|
||||
logger.debug("Socket controller received new file handle")
|
||||
Task { [handler, logger = UncheckedSendable(logger)] in
|
||||
if((await handler?(new, new)) == true) {
|
||||
logger.value.debug("Socket controller handled data, wait for more data")
|
||||
await new.waitForDataInBackgroundAndNotifyOnMainActor()
|
||||
} else {
|
||||
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)
|
||||
}
|
||||
|
||||
}
|
||||
|
@ -32,3 +32,9 @@ SecretKit is a collection of protocols describing secrets and stores.
|
||||
### Authentication Persistence
|
||||
|
||||
- ``PersistedAuthenticationContext``
|
||||
|
||||
### Errors
|
||||
|
||||
- ``KeychainError``
|
||||
- ``SigningError``
|
||||
- ``SecurityError``
|
||||
|
@ -1,7 +1,7 @@
|
||||
import Foundation
|
||||
|
||||
/// Type eraser for Secret.
|
||||
public struct AnySecret: Secret {
|
||||
public struct AnySecret: Secret, @unchecked Sendable {
|
||||
|
||||
let base: Any
|
||||
private let hashable: AnyHashable
|
||||
|
@ -2,18 +2,18 @@ import Foundation
|
||||
import Combine
|
||||
|
||||
/// Type eraser for SecretStore.
|
||||
public class AnySecretStore: SecretStore {
|
||||
public class AnySecretStore: SecretStore, @unchecked Sendable {
|
||||
|
||||
let base: Any
|
||||
private let _isAvailable: () -> Bool
|
||||
private let _id: () -> UUID
|
||||
private let _name: () -> String
|
||||
private let _secrets: () -> [AnySecret]
|
||||
private let _sign: (Data, AnySecret, SigningRequestProvenance) throws -> Data
|
||||
private let _existingPersistedAuthenticationContext: (AnySecret) -> PersistedAuthenticationContext?
|
||||
private let _persistAuthentication: (AnySecret, TimeInterval) throws -> Void
|
||||
|
||||
private var sink: AnyCancellable?
|
||||
private let _isAvailable: @Sendable () -> Bool
|
||||
private let _id: @Sendable () -> UUID
|
||||
private let _name: @Sendable () -> String
|
||||
private let _secrets: @Sendable () -> [AnySecret]
|
||||
private let _sign: @Sendable (Data, AnySecret, SigningRequestProvenance) async throws -> Data
|
||||
private let _verify: @Sendable (Data, Data, AnySecret) async throws -> Bool
|
||||
private let _existingPersistedAuthenticationContext: @Sendable (AnySecret) async -> PersistedAuthenticationContext?
|
||||
private let _persistAuthentication: @Sendable (AnySecret, TimeInterval) async throws -> Void
|
||||
private let _reloadSecrets: @Sendable () async -> Void
|
||||
|
||||
public init<SecretStoreType>(_ secretStore: SecretStoreType) where SecretStoreType: SecretStore {
|
||||
base = secretStore
|
||||
@ -21,12 +21,11 @@ public class AnySecretStore: SecretStore {
|
||||
_name = { secretStore.name }
|
||||
_id = { secretStore.id }
|
||||
_secrets = { secretStore.secrets.map { AnySecret($0) } }
|
||||
_sign = { try secretStore.sign(data: $0, with: $1.base as! SecretStoreType.SecretType, for: $2) }
|
||||
_existingPersistedAuthenticationContext = { secretStore.existingPersistedAuthenticationContext(secret: $0.base as! SecretStoreType.SecretType) }
|
||||
_persistAuthentication = { try secretStore.persistAuthentication(secret: $0.base as! SecretStoreType.SecretType, forDuration: $1) }
|
||||
sink = secretStore.objectWillChange.sink { _ in
|
||||
self.objectWillChange.send()
|
||||
}
|
||||
_sign = { try await 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) }
|
||||
_existingPersistedAuthenticationContext = { await secretStore.existingPersistedAuthenticationContext(secret: $0.base as! SecretStoreType.SecretType) }
|
||||
_persistAuthentication = { try await secretStore.persistAuthentication(secret: $0.base as! SecretStoreType.SecretType, forDuration: $1) }
|
||||
_reloadSecrets = { await secretStore.reloadSecrets() }
|
||||
}
|
||||
|
||||
public var isAvailable: Bool {
|
||||
@ -45,43 +44,51 @@ public class AnySecretStore: SecretStore {
|
||||
return _secrets()
|
||||
}
|
||||
|
||||
public func sign(data: Data, with secret: AnySecret, for provenance: SigningRequestProvenance) throws -> Data {
|
||||
try _sign(data, secret, provenance)
|
||||
public func sign(data: Data, with secret: AnySecret, for provenance: SigningRequestProvenance) async throws -> Data {
|
||||
try await _sign(data, secret, provenance)
|
||||
}
|
||||
|
||||
public func existingPersistedAuthenticationContext(secret: AnySecret) -> PersistedAuthenticationContext? {
|
||||
_existingPersistedAuthenticationContext(secret)
|
||||
public func verify(signature: Data, for data: Data, with secret: AnySecret) async throws -> Bool {
|
||||
try await _verify(signature, data, secret)
|
||||
}
|
||||
|
||||
public func persistAuthentication(secret: AnySecret, forDuration duration: TimeInterval) throws {
|
||||
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 class AnySecretStoreModifiable: AnySecretStore, SecretStoreModifiable {
|
||||
public final class AnySecretStoreModifiable: AnySecretStore, SecretStoreModifiable, @unchecked Sendable {
|
||||
|
||||
private let _create: (String, Bool) throws -> Void
|
||||
private let _delete: (AnySecret) throws -> Void
|
||||
private let _update: (AnySecret, String) throws -> Void
|
||||
private let _create: @Sendable (String, Bool) async throws -> Void
|
||||
private let _delete: @Sendable (AnySecret) async throws -> Void
|
||||
private let _update: @Sendable (AnySecret, String) async throws -> Void
|
||||
|
||||
public init<SecretStoreType>(modifiable secretStore: SecretStoreType) where SecretStoreType: SecretStoreModifiable {
|
||||
_create = { try secretStore.create(name: $0, requiresAuthentication: $1) }
|
||||
_delete = { try secretStore.delete(secret: $0.base as! SecretStoreType.SecretType) }
|
||||
_update = { try secretStore.update(secret: $0.base as! SecretStoreType.SecretType, name: $1) }
|
||||
_create = { try await secretStore.create(name: $0, requiresAuthentication: $1) }
|
||||
_delete = { try await secretStore.delete(secret: $0.base as! SecretStoreType.SecretType) }
|
||||
_update = { try await secretStore.update(secret: $0.base as! SecretStoreType.SecretType, name: $1) }
|
||||
super.init(secretStore)
|
||||
}
|
||||
|
||||
public func create(name: String, requiresAuthentication: Bool) throws {
|
||||
try _create(name, requiresAuthentication)
|
||||
public func create(name: String, requiresAuthentication: Bool) async throws {
|
||||
try await _create(name, requiresAuthentication)
|
||||
}
|
||||
|
||||
public func delete(secret: AnySecret) throws {
|
||||
try _delete(secret)
|
||||
public func delete(secret: AnySecret) async throws {
|
||||
try await _delete(secret)
|
||||
}
|
||||
|
||||
public func update(secret: AnySecret, name: String) throws {
|
||||
try _update(secret, name)
|
||||
public func update(secret: AnySecret, name: String) async throws {
|
||||
try await _update(secret, name)
|
||||
}
|
||||
|
||||
}
|
||||
|
71
Sources/Packages/Sources/SecretKit/KeychainTypes.swift
Normal file
71
Sources/Packages/Sources/SecretKit/KeychainTypes.swift
Normal file
@ -0,0 +1,71 @@
|
||||
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()
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
}
|
@ -0,0 +1,128 @@
|
||||
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"
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
}
|
@ -2,7 +2,7 @@ import Foundation
|
||||
import CryptoKit
|
||||
|
||||
/// Generates OpenSSH representations of Secrets.
|
||||
public struct OpenSSHKeyWriter {
|
||||
public struct OpenSSHKeyWriter: Sendable {
|
||||
|
||||
/// Initializes the writer.
|
||||
public init() {
|
||||
@ -64,6 +64,10 @@ extension OpenSSHKeyWriter {
|
||||
switch algorithm {
|
||||
case .ellipticCurve:
|
||||
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"
|
||||
}
|
||||
}
|
||||
|
||||
@ -76,6 +80,9 @@ extension OpenSSHKeyWriter {
|
||||
switch algorithm {
|
||||
case .ellipticCurve:
|
||||
return "nistp" + String(describing: length)
|
||||
case .rsa:
|
||||
// All RSA keys use the same 512 bit hash function
|
||||
return "rsa-sha2-512"
|
||||
}
|
||||
}
|
||||
|
||||
|
@ -1,7 +1,7 @@
|
||||
import Foundation
|
||||
|
||||
/// Reads OpenSSH protocol data.
|
||||
public class OpenSSHReader {
|
||||
public final class OpenSSHReader {
|
||||
|
||||
var remaining: Data
|
||||
|
||||
|
@ -2,9 +2,9 @@ import Foundation
|
||||
import OSLog
|
||||
|
||||
/// Controller responsible for writing public keys to disk, so that they're easily accessible by scripts.
|
||||
public class PublicKeyFileStoreController {
|
||||
public final class PublicKeyFileStoreController: Sendable {
|
||||
|
||||
private let logger = Logger()
|
||||
private let logger = Logger(subsystem: "com.maxgoedjen.secretive.secretagent", category: "PublicKeyFileStoreController")
|
||||
private let directory: String
|
||||
private let keyWriter = OpenSSHKeyWriter()
|
||||
|
||||
@ -15,15 +15,23 @@ public class PublicKeyFileStoreController {
|
||||
|
||||
/// Writes out the keys specified to disk.
|
||||
/// - Parameter secrets: The Secrets to generate keys for.
|
||||
/// - Parameter clear: Whether or not the directory should be erased before writing keys.
|
||||
/// - Parameter clear: Whether or not any untracked files in the directory should be removed.
|
||||
public func generatePublicKeys(for secrets: [AnySecret], clear: Bool = false) throws {
|
||||
logger.log("Writing public keys to disk")
|
||||
if clear {
|
||||
try? FileManager.default.removeItem(at: URL(fileURLWithPath: directory))
|
||||
let validPaths = Set(secrets.map { publicKeyPath(for: $0) }).union(Set(secrets.map { sshCertificatePath(for: $0) }))
|
||||
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)
|
||||
for secret in secrets {
|
||||
let path = path(for: secret)
|
||||
let path = publicKeyPath(for: secret)
|
||||
guard let data = keyWriter.openSSHString(secret: secret).data(using: .utf8) else { continue }
|
||||
FileManager.default.createFile(atPath: path, contents: data, attributes: nil)
|
||||
}
|
||||
@ -34,9 +42,30 @@ public class PublicKeyFileStoreController {
|
||||
/// - Parameter secret: The Secret to return the path for.
|
||||
/// - 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.
|
||||
public func path<SecretType: Secret>(for secret: SecretType) -> String {
|
||||
public func publicKeyPath<SecretType: Secret>(for secret: SecretType) -> String {
|
||||
let minimalHex = keyWriter.openSSHMD5Fingerprint(secret: secret).replacingOccurrences(of: ":", with: "")
|
||||
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")
|
||||
}
|
||||
|
||||
}
|
||||
|
@ -1,14 +1,21 @@
|
||||
import Foundation
|
||||
import Combine
|
||||
import Observation
|
||||
import Synchronization
|
||||
|
||||
/// A "Store Store," which holds a list of type-erased stores.
|
||||
public class SecretStoreList: ObservableObject {
|
||||
@Observable public final class SecretStoreList: Sendable {
|
||||
|
||||
/// The Stores managed by the SecretStoreList.
|
||||
@Published public var stores: [AnySecretStore] = []
|
||||
public var stores: [AnySecretStore] {
|
||||
__stores.withLock { $0 }
|
||||
}
|
||||
private let __stores: Mutex<[AnySecretStore]> = .init([])
|
||||
|
||||
/// A modifiable store, if one is available.
|
||||
@Published public var modifiableStore: AnySecretStoreModifiable?
|
||||
private var sinks: [AnyCancellable] = []
|
||||
public var modifiableStore: AnySecretStoreModifiable? {
|
||||
__modifiableStore.withLock { $0 }
|
||||
}
|
||||
private let __modifiableStore: Mutex<AnySecretStoreModifiable?> = .init(nil)
|
||||
|
||||
/// Initializes a SecretStoreList.
|
||||
public init() {
|
||||
@ -16,31 +23,33 @@ public class SecretStoreList: ObservableObject {
|
||||
|
||||
/// Adds a non-type-erased SecretStore to the list.
|
||||
public func add<SecretStoreType: SecretStore>(store: SecretStoreType) {
|
||||
addInternal(store: AnySecretStore(store))
|
||||
__stores.withLock {
|
||||
$0.append(AnySecretStore(store))
|
||||
}
|
||||
}
|
||||
|
||||
/// Adds a non-type-erased modifiable SecretStore.
|
||||
public func add<SecretStoreType: SecretStoreModifiable>(store: SecretStoreType) {
|
||||
let modifiable = AnySecretStoreModifiable(modifiable: store)
|
||||
modifiableStore = modifiable
|
||||
addInternal(store: modifiable)
|
||||
__modifiableStore.withLock {
|
||||
$0 = modifiable
|
||||
}
|
||||
__stores.withLock {
|
||||
$0.append(modifiable)
|
||||
}
|
||||
}
|
||||
|
||||
/// A boolean describing whether there are any Stores available.
|
||||
public var anyAvailable: Bool {
|
||||
stores.reduce(false, { $0 || $1.isAvailable })
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
extension SecretStoreList {
|
||||
|
||||
private func addInternal(store: AnySecretStore) {
|
||||
stores.append(store)
|
||||
let sink = store.objectWillChange.sink {
|
||||
self.objectWillChange.send()
|
||||
__stores.withLock {
|
||||
$0.reduce(false, { $0 || $1.isAvailable })
|
||||
}
|
||||
}
|
||||
|
||||
public var allSecrets: [AnySecret] {
|
||||
__stores.withLock {
|
||||
$0.flatMap(\.secrets)
|
||||
}
|
||||
sinks.append(sink)
|
||||
}
|
||||
|
||||
}
|
||||
|
@ -1,7 +1,7 @@
|
||||
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 {
|
||||
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.
|
||||
|
@ -1,7 +1,7 @@
|
||||
import Foundation
|
||||
|
||||
/// The base protocol for describing a Secret
|
||||
public protocol Secret: Identifiable, Hashable {
|
||||
public protocol Secret: Identifiable, Hashable, Sendable {
|
||||
|
||||
/// A user-facing string identifying the Secret.
|
||||
var name: String { get }
|
||||
@ -17,9 +17,10 @@ public protocol Secret: Identifiable, Hashable {
|
||||
}
|
||||
|
||||
/// The type of algorithm the Secret uses. Currently, only elliptic curve algorithms are supported.
|
||||
public enum Algorithm: Hashable {
|
||||
public enum Algorithm: Hashable, Sendable {
|
||||
|
||||
case ellipticCurve
|
||||
case rsa
|
||||
|
||||
/// Initializes the Algorithm with a secAttr representation of an algorithm.
|
||||
/// - Parameter secAttr: the secAttr, represented as an NSNumber.
|
||||
@ -28,8 +29,19 @@ public enum Algorithm: Hashable {
|
||||
switch secAttrString {
|
||||
case kSecAttrKeyTypeEC:
|
||||
self = .ellipticCurve
|
||||
case kSecAttrKeyTypeRSA:
|
||||
self = .rsa
|
||||
default:
|
||||
fatalError()
|
||||
}
|
||||
}
|
||||
|
||||
public var secAttrKeyType: CFString {
|
||||
switch self {
|
||||
case .ellipticCurve:
|
||||
return kSecAttrKeyTypeEC
|
||||
case .rsa:
|
||||
return kSecAttrKeyTypeRSA
|
||||
}
|
||||
}
|
||||
}
|
||||
|
@ -2,7 +2,7 @@ import Foundation
|
||||
import Combine
|
||||
|
||||
/// Manages access to Secrets, and performs signature operations on data using those Secrets.
|
||||
public protocol SecretStore: ObservableObject, Identifiable {
|
||||
public protocol SecretStore: Identifiable, Sendable {
|
||||
|
||||
associatedtype SecretType: Secret
|
||||
|
||||
@ -21,20 +21,31 @@ public protocol SecretStore: ObservableObject, Identifiable {
|
||||
/// - secret: The ``Secret`` to sign with.
|
||||
/// - provenance: A ``SigningRequestProvenance`` describing where the request came from.
|
||||
/// - Returns: The signed data.
|
||||
func sign(data: Data, with secret: SecretType, for provenance: SigningRequestProvenance) throws -> Data
|
||||
func sign(data: Data, with secret: SecretType, for provenance: SigningRequestProvenance) async throws -> Data
|
||||
|
||||
/// 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) -> PersistedAuthenticationContext?
|
||||
func existingPersistedAuthenticationContext(secret: SecretType) async -> PersistedAuthenticationContext?
|
||||
|
||||
/// Persists user authorization for access to a secret.
|
||||
/// - Parameters:
|
||||
/// - secret: The ``Secret`` to persist the authorization 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.
|
||||
func persistAuthentication(secret: SecretType, forDuration duration: TimeInterval) throws
|
||||
func persistAuthentication(secret: SecretType, forDuration duration: TimeInterval) async throws
|
||||
|
||||
/// Requests that the store reload secrets from any backing store, if neccessary.
|
||||
func reloadSecrets() async
|
||||
|
||||
}
|
||||
|
||||
@ -45,18 +56,18 @@ public protocol SecretStoreModifiable: SecretStore {
|
||||
/// - Parameters:
|
||||
/// - 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.
|
||||
func create(name: String, requiresAuthentication: Bool) throws
|
||||
func create(name: String, requiresAuthentication: Bool) async throws
|
||||
|
||||
/// Deletes a Secret in the store.
|
||||
/// - Parameters:
|
||||
/// - secret: The ``Secret`` to delete.
|
||||
func delete(secret: SecretType) throws
|
||||
func delete(secret: SecretType) async throws
|
||||
|
||||
/// Updates the name of a Secret in the store.
|
||||
/// - Parameters:
|
||||
/// - secret: The ``Secret`` to update.
|
||||
/// - name: The new name for the Secret.
|
||||
func update(secret: SecretType, name: String) throws
|
||||
func update(secret: SecretType, name: String) async throws
|
||||
|
||||
}
|
||||
|
||||
|
@ -1,37 +1,41 @@
|
||||
import Foundation
|
||||
import Observation
|
||||
import Security
|
||||
import CryptoTokenKit
|
||||
import CryptoKit
|
||||
import LocalAuthentication
|
||||
import SecretKit
|
||||
import Synchronization
|
||||
|
||||
extension SecureEnclave {
|
||||
|
||||
/// An implementation of Store backed by the Secure Enclave.
|
||||
public class Store: SecretStoreModifiable {
|
||||
@Observable public final class Store: SecretStoreModifiable {
|
||||
|
||||
public var isAvailable: Bool {
|
||||
// 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")
|
||||
CryptoKit.SecureEnclave.isAvailable
|
||||
}
|
||||
public let id = UUID()
|
||||
public let name = NSLocalizedString("Secure Enclave", comment: "Secure Enclave")
|
||||
@Published public private(set) var secrets: [Secret] = []
|
||||
public let name = String(localized: "secure_enclave")
|
||||
public var secrets: [Secret] {
|
||||
_secrets.withLock { $0 }
|
||||
}
|
||||
private let _secrets: Mutex<[Secret]> = .init([])
|
||||
|
||||
private var persistedAuthenticationContexts: [Secret: PersistentAuthenticationContext] = [:]
|
||||
private let persistedAuthenticationContexts: Mutex<[Secret: PersistentAuthenticationContext]> = .init([:])
|
||||
|
||||
/// Initializes a Store.
|
||||
public init() {
|
||||
DistributedNotificationCenter.default().addObserver(forName: .secretStoreUpdated, object: nil, queue: .main) { _ in
|
||||
self.reloadSecrets(notifyAgent: false)
|
||||
Task {
|
||||
for await _ in DistributedNotificationCenter.default().notifications(named: .secretStoreUpdated) {
|
||||
await reloadSecretsInternal(notifyAgent: false)
|
||||
}
|
||||
}
|
||||
loadSecrets()
|
||||
}
|
||||
|
||||
// MARK: Public API
|
||||
|
||||
public func create(name: String, requiresAuthentication: Bool) throws {
|
||||
public func create(name: String, requiresAuthentication: Bool) async throws {
|
||||
var accessError: SecurityError?
|
||||
let flags: SecAccessControlCreateFlags
|
||||
if requiresAuthentication {
|
||||
@ -48,7 +52,7 @@ extension SecureEnclave {
|
||||
throw error.takeRetainedValue() as Error
|
||||
}
|
||||
|
||||
let attributes = [
|
||||
let attributes = KeychainDictionary([
|
||||
kSecAttrLabel: name,
|
||||
kSecAttrKeyType: Constants.keyType,
|
||||
kSecAttrTokenID: kSecAttrTokenIDSecureEnclave,
|
||||
@ -57,7 +61,7 @@ extension SecureEnclave {
|
||||
kSecAttrIsPermanent: true,
|
||||
kSecAttrAccessControl: access
|
||||
]
|
||||
] as CFDictionary
|
||||
])
|
||||
|
||||
var createKeyError: SecurityError?
|
||||
let keypair = SecKeyCreateRandomKey(attributes, &createKeyError)
|
||||
@ -68,49 +72,82 @@ extension SecureEnclave {
|
||||
throw KeychainError(statusCode: nil)
|
||||
}
|
||||
try savePublicKey(publicKey, name: name)
|
||||
reloadSecrets()
|
||||
await reloadSecretsInternal()
|
||||
}
|
||||
|
||||
public func delete(secret: Secret) throws {
|
||||
let deleteAttributes = [
|
||||
public func delete(secret: Secret) async throws {
|
||||
let deleteAttributes = KeychainDictionary([
|
||||
kSecClass: kSecClassKey,
|
||||
kSecAttrApplicationLabel: secret.id as CFData
|
||||
] as CFDictionary
|
||||
])
|
||||
let status = SecItemDelete(deleteAttributes)
|
||||
if status != errSecSuccess {
|
||||
throw KeychainError(statusCode: status)
|
||||
}
|
||||
reloadSecrets()
|
||||
await reloadSecretsInternal()
|
||||
}
|
||||
|
||||
public func update(secret: Secret, name: String) throws {
|
||||
let updateQuery = [
|
||||
public func update(secret: Secret, name: String) async throws {
|
||||
let updateQuery = KeychainDictionary([
|
||||
kSecClass: kSecClassKey,
|
||||
kSecAttrApplicationLabel: secret.id as CFData
|
||||
] as CFDictionary
|
||||
])
|
||||
|
||||
let updatedAttributes = [
|
||||
let updatedAttributes = KeychainDictionary([
|
||||
kSecAttrLabel: name,
|
||||
] as CFDictionary
|
||||
])
|
||||
|
||||
let status = SecItemUpdate(updateQuery, updatedAttributes)
|
||||
if status != errSecSuccess {
|
||||
throw KeychainError(statusCode: status)
|
||||
}
|
||||
reloadSecrets()
|
||||
await reloadSecretsInternal()
|
||||
}
|
||||
|
||||
public func sign(data: Data, with secret: SecretType, for provenance: SigningRequestProvenance) throws -> Data {
|
||||
let context: LAContext
|
||||
if let existing = persistedAuthenticationContexts[secret], existing.valid {
|
||||
context = existing.context
|
||||
} else {
|
||||
public func sign(data: Data, with secret: Secret, for provenance: SigningRequestProvenance) throws -> Data {
|
||||
let context: Mutex<LAContext>
|
||||
// if let existing = persistedAuthenticationContexts.withLock({ $0 })[secret], existing.valid {
|
||||
// context = existing.context
|
||||
// } else {
|
||||
let newContext = LAContext()
|
||||
newContext.localizedCancelTitle = "Deny"
|
||||
context = newContext
|
||||
newContext.localizedCancelTitle = String(localized: "auth_context_request_deny_button")
|
||||
context = .init(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,
|
||||
kSecAttrKeyClass: kSecAttrKeyClassPrivate,
|
||||
kSecAttrApplicationLabel: secret.id as CFData,
|
||||
@ -119,7 +156,8 @@ extension SecureEnclave {
|
||||
kSecAttrApplicationTag: Constants.keyTag,
|
||||
kSecUseAuthenticationContext: context,
|
||||
kSecReturnRef: true
|
||||
] as CFDictionary
|
||||
])
|
||||
var verifyError: SecurityError?
|
||||
var untyped: CFTypeRef?
|
||||
let status = SecItemCopyMatching(attributes, &untyped)
|
||||
if status != errSecSuccess {
|
||||
@ -129,40 +167,49 @@ extension SecureEnclave {
|
||||
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)
|
||||
let verified = SecKeyVerifySignature(key, .ecdsaSignatureMessageX962SHA256, data as CFData, signature as CFData, &verifyError)
|
||||
if !verified, let verifyError {
|
||||
if verifyError.takeUnretainedValue() ~= .verifyError {
|
||||
return false
|
||||
} else {
|
||||
throw SigningError(error: verifyError)
|
||||
}
|
||||
}
|
||||
return signature as Data
|
||||
return verified
|
||||
}
|
||||
|
||||
public func existingPersistedAuthenticationContext(secret: Secret) -> PersistedAuthenticationContext? {
|
||||
guard let persisted = persistedAuthenticationContexts[secret], persisted.valid else { return nil }
|
||||
guard let persisted = persistedAuthenticationContexts.withLock({ $0 })[secret], persisted.valid else { return nil }
|
||||
return persisted
|
||||
}
|
||||
|
||||
public func persistAuthentication(secret: Secret, forDuration duration: TimeInterval) throws {
|
||||
let newContext = LAContext()
|
||||
newContext.touchIDAuthenticationAllowableReuseDuration = duration
|
||||
newContext.localizedCancelTitle = "Deny"
|
||||
newContext.localizedCancelTitle = String(localized: "auth_context_request_deny_button")
|
||||
|
||||
let formatter = DateComponentsFormatter()
|
||||
formatter.unitsStyle = .spellOut
|
||||
formatter.allowedUnits = [.hour, .minute, .day]
|
||||
|
||||
if let durationString = formatter.string(from: duration) {
|
||||
newContext.localizedReason = "unlock secret \"\(secret.name)\" for \(durationString)"
|
||||
newContext.localizedReason = String(localized: "auth_context_persist_for_duration_\(secret.name)_\(durationString)")
|
||||
} else {
|
||||
newContext.localizedReason = "unlock secret \"\(secret.name)\""
|
||||
newContext.localizedReason = String(localized: "auth_context_persist_for_duration_unknown_\(secret.name)")
|
||||
}
|
||||
newContext.evaluatePolicy(LAPolicy.deviceOwnerAuthentication, localizedReason: newContext.localizedReason) { [weak self] success, _ in
|
||||
guard success else { return }
|
||||
guard success, let self else { return }
|
||||
let context = PersistentAuthenticationContext(secret: secret, context: newContext, duration: duration)
|
||||
self?.persistedAuthenticationContexts[secret] = context
|
||||
self.persistedAuthenticationContexts.withLock {
|
||||
$0[secret] = context
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
public func reloadSecrets() async {
|
||||
await reloadSecretsInternal(notifyAgent: false)
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
}
|
||||
@ -171,18 +218,23 @@ extension SecureEnclave.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.
|
||||
private func reloadSecrets(notifyAgent: Bool = true) {
|
||||
secrets.removeAll()
|
||||
private func reloadSecretsInternal(notifyAgent: Bool = true) async {
|
||||
let before = secrets
|
||||
_secrets.withLock {
|
||||
$0.removeAll()
|
||||
}
|
||||
loadSecrets()
|
||||
NotificationCenter.default.post(name: .secretStoreReloaded, object: self)
|
||||
if notifyAgent {
|
||||
DistributedNotificationCenter.default().postNotificationName(.secretStoreUpdated, object: nil, deliverImmediately: true)
|
||||
if secrets != before {
|
||||
NotificationCenter.default.post(name: .secretStoreReloaded, object: self)
|
||||
if notifyAgent {
|
||||
DistributedNotificationCenter.default().postNotificationName(.secretStoreUpdated, object: nil, deliverImmediately: true)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// Loads all secrets from the store.
|
||||
private func loadSecrets() {
|
||||
let publicAttributes = [
|
||||
let publicAttributes = KeychainDictionary([
|
||||
kSecClass: kSecClassKey,
|
||||
kSecAttrKeyType: SecureEnclave.Constants.keyType,
|
||||
kSecAttrApplicationTag: SecureEnclave.Constants.keyTag,
|
||||
@ -190,11 +242,11 @@ extension SecureEnclave.Store {
|
||||
kSecReturnRef: true,
|
||||
kSecMatchLimit: kSecMatchLimitAll,
|
||||
kSecReturnAttributes: true
|
||||
] as CFDictionary
|
||||
])
|
||||
var publicUntyped: CFTypeRef?
|
||||
SecItemCopyMatching(publicAttributes, &publicUntyped)
|
||||
guard let publicTyped = publicUntyped as? [[CFString: Any]] else { return }
|
||||
let privateAttributes = [
|
||||
let privateAttributes = KeychainDictionary([
|
||||
kSecClass: kSecClassKey,
|
||||
kSecAttrKeyType: SecureEnclave.Constants.keyType,
|
||||
kSecAttrApplicationTag: SecureEnclave.Constants.keyTag,
|
||||
@ -202,7 +254,7 @@ extension SecureEnclave.Store {
|
||||
kSecReturnRef: true,
|
||||
kSecMatchLimit: kSecMatchLimitAll,
|
||||
kSecReturnAttributes: true
|
||||
] as CFDictionary
|
||||
])
|
||||
var privateUntyped: CFTypeRef?
|
||||
SecItemCopyMatching(privateAttributes, &privateUntyped)
|
||||
guard let privateTyped = privateUntyped as? [[CFString: Any]] else { return }
|
||||
@ -217,7 +269,7 @@ extension SecureEnclave.Store {
|
||||
nil)!
|
||||
|
||||
let wrapped: [SecureEnclave.Secret] = publicTyped.map {
|
||||
let name = $0[kSecAttrLabel] as? String ?? "Unnamed"
|
||||
let name = $0[kSecAttrLabel] as? String ?? String(localized: "unnamed_secret")
|
||||
let id = $0[kSecAttrApplicationLabel] as! Data
|
||||
let publicKeyRef = $0[kSecValueRef] as! SecKey
|
||||
let publicKeyAttributes = SecKeyCopyAttributes(publicKeyRef) as! [CFString: Any]
|
||||
@ -232,7 +284,9 @@ extension SecureEnclave.Store {
|
||||
}
|
||||
return SecureEnclave.Secret(id: id, name: name, requiresAuthentication: requiresAuth, publicKey: publicKey)
|
||||
}
|
||||
secrets.append(contentsOf: wrapped)
|
||||
_secrets.withLock {
|
||||
$0.append(contentsOf: wrapped)
|
||||
}
|
||||
}
|
||||
|
||||
/// Saves a public key.
|
||||
@ -240,7 +294,7 @@ extension SecureEnclave.Store {
|
||||
/// - publicKey: The public key to save.
|
||||
/// - name: A user-facing name for the key.
|
||||
private func savePublicKey(_ publicKey: SecKey, name: String) throws {
|
||||
let attributes = [
|
||||
let attributes = KeychainDictionary([
|
||||
kSecClass: kSecClassKey,
|
||||
kSecAttrKeyType: SecureEnclave.Constants.keyType,
|
||||
kSecAttrKeyClass: kSecAttrKeyClassPublic,
|
||||
@ -249,42 +303,20 @@ extension SecureEnclave.Store {
|
||||
kSecAttrIsPermanent: true,
|
||||
kSecReturnData: true,
|
||||
kSecAttrLabel: name
|
||||
] as CFDictionary
|
||||
])
|
||||
let status = SecItemAdd(attributes, nil)
|
||||
if status != errSecSuccess {
|
||||
throw SecureEnclave.KeychainError(statusCode: status)
|
||||
throw 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 {
|
||||
|
||||
enum Constants {
|
||||
static let keyTag = "com.maxgoedjen.secretive.secureenclave.key".data(using: .utf8)! as CFData
|
||||
static let keyType = kSecAttrKeyTypeECSECPrimeRandom
|
||||
static let keyTag = Data("com.maxgoedjen.secretive.secureenclave.key".utf8)
|
||||
static let keyType = kSecAttrKeyTypeECSECPrimeRandom as String
|
||||
static let unauthenticatedThreshold: TimeInterval = 0.05
|
||||
}
|
||||
|
||||
@ -293,12 +325,12 @@ extension SecureEnclave {
|
||||
extension SecureEnclave {
|
||||
|
||||
/// A context describing a persisted authentication.
|
||||
private struct PersistentAuthenticationContext: PersistedAuthenticationContext {
|
||||
private final class PersistentAuthenticationContext: PersistedAuthenticationContext {
|
||||
|
||||
/// The Secret to persist authentication for.
|
||||
let secret: Secret
|
||||
/// The LAContext used to authorize the persistent context.
|
||||
let context: LAContext
|
||||
nonisolated(unsafe) let context: LAContext
|
||||
/// An expiration date for the context.
|
||||
/// - Note - Monotonic time instead of Date() to prevent people setting the clock back.
|
||||
let monotonicExpiration: UInt64
|
||||
|
@ -6,9 +6,3 @@
|
||||
|
||||
- ``Secret``
|
||||
- ``Store``
|
||||
|
||||
### Errors
|
||||
|
||||
- ``KeychainError``
|
||||
- ``SigningError``
|
||||
- ``SecurityError``
|
||||
|
@ -1,35 +1,51 @@
|
||||
import Foundation
|
||||
import Synchronization
|
||||
import Observation
|
||||
import Security
|
||||
import CryptoTokenKit
|
||||
import LocalAuthentication
|
||||
import SecretKit
|
||||
|
||||
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.
|
||||
public class Store: SecretStore {
|
||||
@Observable public final 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 private(set) var name = NSLocalizedString("Smart Card", comment: "Smart Card")
|
||||
@Published public private(set) var secrets: [Secret] = []
|
||||
private let watcher = TKTokenWatcher()
|
||||
private var tokenID: String?
|
||||
public var name: String {
|
||||
state.withLock { $0.name }
|
||||
}
|
||||
public var secrets: [Secret] {
|
||||
state.withLock { $0.secrets }
|
||||
}
|
||||
|
||||
/// Initializes a Store.
|
||||
public init() {
|
||||
tokenID = watcher.nonSecureEnclaveTokens.first
|
||||
watcher.setInsertionHandler { string in
|
||||
guard self.tokenID == nil else { return }
|
||||
guard !string.contains("setoken") else { return }
|
||||
|
||||
self.tokenID = string
|
||||
self.reloadSecrets()
|
||||
self.watcher.addRemovalHandler(self.smartcardRemoved, forTokenID: string)
|
||||
}
|
||||
if let tokenID = tokenID {
|
||||
self.isAvailable = true
|
||||
self.watcher.addRemovalHandler(self.smartcardRemoved, forTokenID: tokenID)
|
||||
state.withLock { state in
|
||||
if let tokenID = state.tokenID {
|
||||
state.isAvailable = true
|
||||
state.watcher.addRemovalHandler(self.smartcardRemoved, forTokenID: tokenID)
|
||||
}
|
||||
state.watcher.setInsertionHandler { id in
|
||||
// Setting insertion handler will cause it to be called immediately.
|
||||
// Make a thread jump so we don't hit a recursive lock attempt.
|
||||
Task {
|
||||
self.smartcardInserted(for: id)
|
||||
}
|
||||
}
|
||||
}
|
||||
loadSecrets()
|
||||
}
|
||||
@ -44,19 +60,19 @@ extension SmartCard {
|
||||
fatalError("Keys must be deleted on the smart card.")
|
||||
}
|
||||
|
||||
public func sign(data: Data, with secret: SecretType, for provenance: SigningRequestProvenance) throws -> Data {
|
||||
guard let tokenID = tokenID else { fatalError() }
|
||||
public func sign(data: Data, with secret: Secret, for provenance: SigningRequestProvenance) throws -> Data {
|
||||
guard let tokenID = state.withLock({ $0.tokenID }) else { fatalError() }
|
||||
let context = LAContext()
|
||||
context.localizedReason = "sign a request from \"\(provenance.origin.displayName)\" using secret \"\(secret.name)\""
|
||||
context.localizedCancelTitle = "Deny"
|
||||
let attributes = [
|
||||
context.localizedReason = String(localized: "auth_context_request_signature_description_\(provenance.origin.displayName)_\(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
|
||||
] as CFDictionary
|
||||
])
|
||||
var untyped: CFTypeRef?
|
||||
let status = SecItemCopyMatching(attributes, &untyped)
|
||||
if status != errSecSuccess {
|
||||
@ -67,26 +83,45 @@ extension SmartCard {
|
||||
}
|
||||
let key = untypedSafe as! SecKey
|
||||
var signError: SecurityError?
|
||||
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 {
|
||||
guard let signature = SecKeyCreateSignature(key, signatureAlgorithm(for: secret, allowRSA: true), data as CFData, &signError) else {
|
||||
throw SigningError(error: signError)
|
||||
}
|
||||
return signature as Data
|
||||
}
|
||||
|
||||
public func verify(signature: Data, for data: Data, with secret: Secret) throws -> Bool {
|
||||
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: SmartCard.Secret) -> PersistedAuthenticationContext? {
|
||||
public func existingPersistedAuthenticationContext(secret: Secret) -> PersistedAuthenticationContext? {
|
||||
nil
|
||||
}
|
||||
|
||||
public func persistAuthentication(secret: SmartCard.Secret, forDuration: TimeInterval) throws {
|
||||
public func persistAuthentication(secret: Secret, forDuration: TimeInterval) throws {
|
||||
}
|
||||
|
||||
/// Reloads all secrets from the store.
|
||||
public func reloadSecrets() {
|
||||
reloadSecretsInternal()
|
||||
}
|
||||
|
||||
}
|
||||
@ -95,56 +130,66 @@ extension SmartCard {
|
||||
|
||||
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.
|
||||
/// - Parameter tokenID: The ID of the token that was removed.
|
||||
private func smartcardRemoved(for tokenID: String? = nil) {
|
||||
self.tokenID = nil
|
||||
reloadSecrets()
|
||||
}
|
||||
|
||||
/// Reloads all secrets from the store.
|
||||
private func reloadSecrets() {
|
||||
DispatchQueue.main.async {
|
||||
self.isAvailable = self.tokenID != nil
|
||||
self.secrets.removeAll()
|
||||
self.loadSecrets()
|
||||
state.withLock {
|
||||
$0.tokenID = nil
|
||||
}
|
||||
reloadSecrets()
|
||||
}
|
||||
|
||||
/// Loads all secrets from the store.
|
||||
private func loadSecrets() {
|
||||
guard let tokenID = tokenID else { return }
|
||||
guard let tokenID = state.withLock({ $0.tokenID }) else { return }
|
||||
|
||||
let fallbackName = NSLocalizedString("Smart Card", comment: "Smart Card")
|
||||
if #available(macOS 12.0, *) {
|
||||
if let driverName = watcher.tokenInfo(forTokenID: tokenID)?.driverName {
|
||||
name = driverName
|
||||
let fallbackName = String(localized: "smart_card")
|
||||
state.withLock {
|
||||
if let driverName = $0.watcher.tokenInfo(forTokenID: tokenID)?.driverName {
|
||||
$0.name = driverName
|
||||
} else {
|
||||
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
|
||||
$0.name = fallbackName
|
||||
}
|
||||
}
|
||||
|
||||
let attributes = [
|
||||
let attributes = KeychainDictionary([
|
||||
kSecClass: kSecClassKey,
|
||||
kSecAttrTokenID: tokenID,
|
||||
kSecAttrKeyType: kSecAttrKeyTypeEC, // Restrict to EC
|
||||
kSecReturnRef: true,
|
||||
kSecMatchLimit: kSecMatchLimitAll,
|
||||
kSecReturnAttributes: true
|
||||
] as CFDictionary
|
||||
])
|
||||
var untyped: CFTypeRef?
|
||||
SecItemCopyMatching(attributes, &untyped)
|
||||
guard let typed = untyped as? [[CFString: Any]] else { return }
|
||||
let wrapped: [SmartCard.Secret] = typed.map {
|
||||
let name = $0[kSecAttrLabel] as? String ?? "Unnamed"
|
||||
let wrapped = typed.map {
|
||||
let name = $0[kSecAttrLabel] as? String ?? String(localized: "unnamed_secret")
|
||||
let tokenID = $0[kSecAttrApplicationLabel] as! Data
|
||||
let algorithm = Algorithm(secAttr: $0[kSecAttrKeyType] as! NSNumber)
|
||||
let keySize = $0[kSecAttrKeySizeInBits] as! Int
|
||||
@ -154,7 +199,91 @@ extension SmartCard.Store {
|
||||
let publicKey = publicKeyAttributes[kSecValueData] as! Data
|
||||
return SmartCard.Secret(id: tokenID, name: name, algorithm: algorithm, keySize: keySize, publicKey: publicKey)
|
||||
}
|
||||
secrets.append(contentsOf: wrapped)
|
||||
state.withLock {
|
||||
$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()
|
||||
}
|
||||
}
|
||||
|
||||
}
|
||||
@ -167,25 +296,3 @@ 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>
|
||||
|
||||
}
|
||||
|
@ -1,54 +1,66 @@
|
||||
import XCTest
|
||||
import Testing
|
||||
import Foundation
|
||||
@testable import Brief
|
||||
|
||||
class ReleaseParsingTests: XCTestCase {
|
||||
|
||||
func testNonCritical() {
|
||||
@Suite struct ReleaseParsingTests {
|
||||
|
||||
@Test
|
||||
func nonCritical() {
|
||||
let release = Release(name: "1.0.0", prerelease: false, html_url: URL(string: "https://example.com")!, body: "Initial release")
|
||||
XCTAssert(release.critical == false)
|
||||
#expect(release.critical == false)
|
||||
}
|
||||
|
||||
func testCritical() {
|
||||
@Test
|
||||
func critical() {
|
||||
let release = Release(name: "1.0.0", prerelease: false, html_url: URL(string: "https://example.com")!, body: "Critical Security Update")
|
||||
XCTAssert(release.critical == true)
|
||||
#expect(release.critical == true)
|
||||
}
|
||||
|
||||
func testOSMissing() {
|
||||
@Test
|
||||
func osMissing() {
|
||||
let release = Release(name: "1.0.0", prerelease: false, html_url: URL(string: "https://example.com")!, body: "Critical Security Update")
|
||||
XCTAssert(release.minimumOSVersion == SemVer("11.0.0"))
|
||||
#expect(release.minimumOSVersion == SemVer("11.0.0"))
|
||||
}
|
||||
|
||||
func testOSPresentWithContentBelow() {
|
||||
@Test
|
||||
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")
|
||||
XCTAssert(release.minimumOSVersion == SemVer("1.2.3"))
|
||||
#expect(release.minimumOSVersion == SemVer("1.2.3"))
|
||||
}
|
||||
|
||||
func testOSPresentAtEnd() {
|
||||
@Test
|
||||
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")
|
||||
XCTAssert(release.minimumOSVersion == SemVer("1.2.3"))
|
||||
#expect(release.minimumOSVersion == SemVer("1.2.3"))
|
||||
}
|
||||
|
||||
func testOSWithMacOSPrefix() {
|
||||
@Test
|
||||
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")
|
||||
XCTAssert(release.minimumOSVersion == SemVer("1.2.3"))
|
||||
#expect(release.minimumOSVersion == SemVer("1.2.3"))
|
||||
}
|
||||
|
||||
func testOSGreaterThanMinimum() {
|
||||
@Test
|
||||
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")
|
||||
XCTAssert(release.minimumOSVersion < SemVer("11.0.0"))
|
||||
#expect(release.minimumOSVersion < SemVer("11.0.0"))
|
||||
}
|
||||
|
||||
func testOSEqualToMinimum() {
|
||||
@Test
|
||||
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")
|
||||
XCTAssert(release.minimumOSVersion <= SemVer("11.2.3"))
|
||||
#expect(release.minimumOSVersion <= SemVer("11.2.3"))
|
||||
}
|
||||
|
||||
func testOSLessThanMinimum() {
|
||||
@Test
|
||||
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")
|
||||
XCTAssert(release.minimumOSVersion > SemVer("1.0.0"))
|
||||
#expect(release.minimumOSVersion > SemVer("1.0.0"))
|
||||
}
|
||||
|
||||
func testGreatestSelectedIfOldPatchIsPublishedLater() {
|
||||
@Test
|
||||
func greatestSelectedIfOldPatchIsPublishedLater() async throws {
|
||||
// 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.
|
||||
let updater = Updater(checkOnLaunch: false, osVersion: SemVer("2.2.3"), currentVersion: SemVer("1.0.0"))
|
||||
@ -60,16 +72,13 @@ class ReleaseParsingTests: XCTestCase {
|
||||
Release(name: "1.0.2", prerelease: false, html_url: URL(string: "https://example.com")!, body: "Emergency patch! Minimum macOS Version: 1.2.3"),
|
||||
]
|
||||
|
||||
let expectation = XCTestExpectation()
|
||||
updater.evaluate(releases: releases)
|
||||
DispatchQueue.main.async {
|
||||
XCTAssert(updater.update == two)
|
||||
expectation.fulfill()
|
||||
}
|
||||
wait(for: [expectation], timeout: 1)
|
||||
await updater.evaluate(releases: releases)
|
||||
try await Task.sleep(nanoseconds: 1)
|
||||
#expect(updater.update == two)
|
||||
}
|
||||
|
||||
func testLatestVersionIsRunnable() {
|
||||
@Test
|
||||
func latestVersionIsRunnable() async throws {
|
||||
// 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.
|
||||
let updater = Updater(checkOnLaunch: false, osVersion: SemVer("1.2.3"), currentVersion: SemVer("1.0.0"))
|
||||
@ -80,16 +89,13 @@ class ReleaseParsingTests: XCTestCase {
|
||||
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"),
|
||||
]
|
||||
let expectation = XCTestExpectation()
|
||||
updater.evaluate(releases: releases)
|
||||
DispatchQueue.main.async {
|
||||
XCTAssert(updater.update == oneOhTwo)
|
||||
expectation.fulfill()
|
||||
}
|
||||
wait(for: [expectation], timeout: 1)
|
||||
await updater.evaluate(releases: releases)
|
||||
try await Task.sleep(nanoseconds: 1)
|
||||
#expect(updater.update == oneOhTwo)
|
||||
}
|
||||
|
||||
func testSorting() {
|
||||
@Test
|
||||
func sorting() {
|
||||
let two = Release(name: "2.0.0", prerelease: false, html_url: URL(string: "https://example.com")!, body: "2.0 available!")
|
||||
let releases = [
|
||||
Release(name: "1.0.0", prerelease: false, html_url: URL(string: "https://example.com")!, body: "Initial release"),
|
||||
@ -98,7 +104,7 @@ class ReleaseParsingTests: XCTestCase {
|
||||
Release(name: "1.0.2", prerelease: false, html_url: URL(string: "https://example.com")!, body: "Emergency patch!"),
|
||||
]
|
||||
let sorted = releases.sorted().reversed().first
|
||||
XCTAssert(sorted == two)
|
||||
#expect(sorted == two)
|
||||
}
|
||||
|
||||
}
|
||||
|
@ -1,51 +1,52 @@
|
||||
import XCTest
|
||||
import Testing
|
||||
import Foundation
|
||||
@testable import Brief
|
||||
|
||||
class SemVerTests: XCTestCase {
|
||||
@Suite struct SemVerTests {
|
||||
|
||||
func testEqual() {
|
||||
@Test func equal() {
|
||||
let current = SemVer("1.0.2")
|
||||
let old = SemVer("1.0.2")
|
||||
XCTAssert(!(current > old))
|
||||
#expect(!(current > old))
|
||||
}
|
||||
|
||||
func testPatchGreaterButMinorLess() {
|
||||
@Test func patchGreaterButMinorLess() {
|
||||
let current = SemVer("1.1.0")
|
||||
let old = SemVer("1.0.2")
|
||||
XCTAssert(current > old)
|
||||
#expect(current > old)
|
||||
}
|
||||
|
||||
func testMajorSameMinorGreater() {
|
||||
@Test func majorSameMinorGreater() {
|
||||
let current = SemVer("1.0.2")
|
||||
let new = SemVer("1.0.3")
|
||||
XCTAssert(current < new)
|
||||
#expect(current < new)
|
||||
}
|
||||
|
||||
func testMajorGreaterMinorLesser() {
|
||||
@Test func majorGreaterMinorLesser() {
|
||||
let current = SemVer("1.0.2")
|
||||
let new = SemVer("2.0.0")
|
||||
XCTAssert(current < new)
|
||||
#expect(current < new)
|
||||
}
|
||||
|
||||
func testRegularParsing() {
|
||||
@Test func regularParsing() {
|
||||
let current = SemVer("1.0.2")
|
||||
XCTAssert(current.versionNumbers == [1, 0, 2])
|
||||
#expect(current.versionNumbers == [1, 0, 2])
|
||||
}
|
||||
|
||||
func testNoPatch() {
|
||||
@Test func noPatch() {
|
||||
let current = SemVer("1.1")
|
||||
XCTAssert(current.versionNumbers == [1, 1, 0])
|
||||
#expect(current.versionNumbers == [1, 1, 0])
|
||||
}
|
||||
|
||||
func testGarbage() {
|
||||
@Test func garbage() {
|
||||
let current = SemVer("Test")
|
||||
XCTAssert(current.versionNumbers == [0, 0, 0])
|
||||
#expect(current.versionNumbers == [0, 0, 0])
|
||||
}
|
||||
|
||||
func testBeta() {
|
||||
@Test func beta() {
|
||||
let current = SemVer("1.0.2")
|
||||
let new = SemVer("1.1.0_beta1")
|
||||
XCTAssert(current < new)
|
||||
#expect(current < new)
|
||||
}
|
||||
|
||||
}
|
||||
|
@ -1,48 +1,48 @@
|
||||
import Foundation
|
||||
import XCTest
|
||||
import Testing
|
||||
import CryptoKit
|
||||
@testable import SecretKit
|
||||
@testable import SecretAgentKit
|
||||
|
||||
class AgentTests: XCTestCase {
|
||||
@Suite struct AgentTests {
|
||||
|
||||
let stubWriter = StubFileHandleWriter()
|
||||
|
||||
// MARK: Identity Listing
|
||||
|
||||
func testEmptyStores() {
|
||||
@Test func emptyStores() async {
|
||||
let stubReader = StubFileHandleReader(availableData: Constants.Requests.requestIdentities)
|
||||
let agent = Agent(storeList: SecretStoreList())
|
||||
agent.handle(reader: stubReader, writer: stubWriter)
|
||||
XCTAssertEqual(stubWriter.data, Constants.Responses.requestIdentitiesEmpty)
|
||||
await agent.handle(reader: stubReader, writer: stubWriter)
|
||||
#expect(stubWriter.data == Constants.Responses.requestIdentitiesEmpty)
|
||||
}
|
||||
|
||||
func testIdentitiesList() {
|
||||
@Test func identitiesList() async {
|
||||
let stubReader = StubFileHandleReader(availableData: Constants.Requests.requestIdentities)
|
||||
let list = storeList(with: [Constants.Secrets.ecdsa256Secret, Constants.Secrets.ecdsa384Secret])
|
||||
let agent = Agent(storeList: list)
|
||||
agent.handle(reader: stubReader, writer: stubWriter)
|
||||
XCTAssertEqual(stubWriter.data, Constants.Responses.requestIdentitiesMultiple)
|
||||
await agent.handle(reader: stubReader, writer: stubWriter)
|
||||
#expect(stubWriter.data == Constants.Responses.requestIdentitiesMultiple)
|
||||
}
|
||||
|
||||
// MARK: Signatures
|
||||
|
||||
func testNoMatchingIdentities() {
|
||||
@Test func noMatchingIdentities() async {
|
||||
let stubReader = StubFileHandleReader(availableData: Constants.Requests.requestSignatureWithNoneMatching)
|
||||
let list = storeList(with: [Constants.Secrets.ecdsa256Secret, Constants.Secrets.ecdsa384Secret])
|
||||
let agent = Agent(storeList: list)
|
||||
agent.handle(reader: stubReader, writer: stubWriter)
|
||||
// XCTAssertEqual(stubWriter.data, Constants.Responses.requestFailure)
|
||||
await agent.handle(reader: stubReader, writer: stubWriter)
|
||||
#expect(stubWriter.data == Constants.Responses.requestFailure)
|
||||
}
|
||||
|
||||
func testSignature() {
|
||||
@Test func signature() async throws {
|
||||
let stubReader = StubFileHandleReader(availableData: Constants.Requests.requestSignature)
|
||||
let requestReader = OpenSSHReader(data: Constants.Requests.requestSignature[5...])
|
||||
_ = requestReader.readNextChunk()
|
||||
let dataToSign = requestReader.readNextChunk()
|
||||
let list = storeList(with: [Constants.Secrets.ecdsa256Secret, Constants.Secrets.ecdsa384Secret])
|
||||
let agent = Agent(storeList: list)
|
||||
agent.handle(reader: stubReader, writer: stubWriter)
|
||||
await agent.handle(reader: stubReader, writer: stubWriter)
|
||||
let outer = OpenSSHReader(data: stubWriter.data[5...])
|
||||
let payload = outer.readNextChunk()
|
||||
let inner = OpenSSHReader(data: payload)
|
||||
@ -61,24 +61,33 @@ class AgentTests: XCTestCase {
|
||||
var rs = r
|
||||
rs.append(s)
|
||||
let signature = try! P256.Signing.ECDSASignature(rawRepresentation: rs)
|
||||
let valid = try! P256.Signing.PublicKey(x963Representation: Constants.Secrets.ecdsa256Secret.publicKey).isValidSignature(signature, for: dataToSign)
|
||||
XCTAssertTrue(valid)
|
||||
let referenceValid = try! P256.Signing.PublicKey(x963Representation: Constants.Secrets.ecdsa256Secret.publicKey).isValidSignature(signature, for: dataToSign)
|
||||
let store = list.stores.first!
|
||||
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
|
||||
|
||||
func testWitnessObjectionStopsRequest() {
|
||||
@Test func witnessObjectionStopsRequest() async {
|
||||
let stubReader = StubFileHandleReader(availableData: Constants.Requests.requestSignature)
|
||||
let list = storeList(with: [Constants.Secrets.ecdsa256Secret])
|
||||
let witness = StubWitness(speakNow: { _,_ in
|
||||
return true
|
||||
}, witness: { _, _ in })
|
||||
let agent = Agent(storeList: list, witness: witness)
|
||||
agent.handle(reader: stubReader, writer: stubWriter)
|
||||
XCTAssertEqual(stubWriter.data, Constants.Responses.requestFailure)
|
||||
await agent.handle(reader: stubReader, writer: stubWriter)
|
||||
#expect(stubWriter.data == Constants.Responses.requestFailure)
|
||||
}
|
||||
|
||||
func testWitnessSignature() {
|
||||
@Test func witnessSignature() async {
|
||||
let stubReader = StubFileHandleReader(availableData: Constants.Requests.requestSignature)
|
||||
let list = storeList(with: [Constants.Secrets.ecdsa256Secret])
|
||||
var witnessed = false
|
||||
@ -88,11 +97,11 @@ class AgentTests: XCTestCase {
|
||||
witnessed = true
|
||||
})
|
||||
let agent = Agent(storeList: list, witness: witness)
|
||||
agent.handle(reader: stubReader, writer: stubWriter)
|
||||
XCTAssertTrue(witnessed)
|
||||
await agent.handle(reader: stubReader, writer: stubWriter)
|
||||
#expect(witnessed)
|
||||
}
|
||||
|
||||
func testRequestTracing() {
|
||||
@Test func requestTracing() async {
|
||||
let stubReader = StubFileHandleReader(availableData: Constants.Requests.requestSignature)
|
||||
let list = storeList(with: [Constants.Secrets.ecdsa256Secret])
|
||||
var speakNowTrace: SigningRequestProvenance! = nil
|
||||
@ -104,32 +113,32 @@ class AgentTests: XCTestCase {
|
||||
witnessTrace = trace
|
||||
})
|
||||
let agent = Agent(storeList: list, witness: witness)
|
||||
agent.handle(reader: stubReader, writer: stubWriter)
|
||||
XCTAssertEqual(witnessTrace, speakNowTrace)
|
||||
XCTAssertEqual(witnessTrace.origin.displayName, "Finder")
|
||||
XCTAssertEqual(witnessTrace.origin.validSignature, true)
|
||||
XCTAssertEqual(witnessTrace.origin.parentPID, 1)
|
||||
await agent.handle(reader: stubReader, writer: stubWriter)
|
||||
#expect(witnessTrace == speakNowTrace)
|
||||
#expect(witnessTrace.origin.displayName == "Finder")
|
||||
#expect(witnessTrace.origin.validSignature == true)
|
||||
#expect(witnessTrace.origin.parentPID == 1)
|
||||
}
|
||||
|
||||
// MARK: Exception Handling
|
||||
|
||||
func testSignatureException() {
|
||||
@Test func signatureException() async {
|
||||
let stubReader = StubFileHandleReader(availableData: Constants.Requests.requestSignature)
|
||||
let list = storeList(with: [Constants.Secrets.ecdsa256Secret, Constants.Secrets.ecdsa384Secret])
|
||||
let store = list.stores.first?.base as! Stub.Store
|
||||
store.shouldThrow = true
|
||||
let agent = Agent(storeList: list)
|
||||
agent.handle(reader: stubReader, writer: stubWriter)
|
||||
XCTAssertEqual(stubWriter.data, Constants.Responses.requestFailure)
|
||||
await agent.handle(reader: stubReader, writer: stubWriter)
|
||||
#expect(stubWriter.data == Constants.Responses.requestFailure)
|
||||
}
|
||||
|
||||
// MARK: Unsupported
|
||||
|
||||
func testUnhandledAdd() {
|
||||
@Test func unhandledAdd() async {
|
||||
let stubReader = StubFileHandleReader(availableData: Constants.Requests.addIdentity)
|
||||
let agent = Agent(storeList: SecretStoreList())
|
||||
agent.handle(reader: stubReader, writer: stubWriter)
|
||||
XCTAssertEqual(stubWriter.data, Constants.Responses.requestFailure)
|
||||
await agent.handle(reader: stubReader, writer: stubWriter)
|
||||
#expect(stubWriter.data == Constants.Responses.requestFailure)
|
||||
}
|
||||
|
||||
}
|
||||
|
@ -1,7 +1,7 @@
|
||||
import Foundation
|
||||
import SecretAgentKit
|
||||
|
||||
class StubFileHandleWriter: FileHandleWriter {
|
||||
class StubFileHandleWriter: FileHandleWriter, @unchecked Sendable {
|
||||
|
||||
var data = Data()
|
||||
|
||||
|
@ -6,7 +6,7 @@ struct Stub {}
|
||||
|
||||
extension Stub {
|
||||
|
||||
public class Store: SecretStore {
|
||||
public final class Store: SecretStore, @unchecked Sendable {
|
||||
|
||||
public let isAvailable = true
|
||||
public let id = UUID()
|
||||
@ -27,7 +27,7 @@ extension Stub {
|
||||
flags,
|
||||
nil) as Any
|
||||
|
||||
let attributes = [
|
||||
let attributes = KeychainDictionary([
|
||||
kSecAttrLabel: name,
|
||||
kSecAttrKeyType: kSecAttrKeyTypeECSECPrimeRandom,
|
||||
kSecAttrKeySizeInBits: size,
|
||||
@ -35,11 +35,10 @@ extension Stub {
|
||||
kSecAttrIsPermanent: true,
|
||||
kSecAttrAccessControl: access
|
||||
]
|
||||
] as CFDictionary
|
||||
])
|
||||
|
||||
var privateKey: SecKey! = nil
|
||||
var publicKey: SecKey! = nil
|
||||
SecKeyGeneratePair(attributes, &publicKey, &privateKey)
|
||||
let privateKey = SecKeyCreateRandomKey(attributes, nil)!
|
||||
let publicKey = SecKeyCopyPublicKey(privateKey)!
|
||||
let publicAttributes = SecKeyCopyAttributes(publicKey) as! [CFString: Any]
|
||||
let privateAttributes = SecKeyCopyAttributes(privateKey) as! [CFString: Any]
|
||||
let publicData = (publicAttributes[kSecValueData] as! Data)
|
||||
@ -53,22 +52,36 @@ extension Stub {
|
||||
guard !shouldThrow else {
|
||||
throw NSError(domain: "test", code: 0, userInfo: nil)
|
||||
}
|
||||
let privateKey = SecKeyCreateWithData(secret.privateKey as CFData, [
|
||||
let privateKey = SecKeyCreateWithData(secret.privateKey as CFData, KeychainDictionary([
|
||||
kSecAttrKeyType: kSecAttrKeyTypeECSECPrimeRandom,
|
||||
kSecAttrKeySizeInBits: secret.keySize,
|
||||
kSecAttrKeyClass: kSecAttrKeyClassPrivate
|
||||
] as CFDictionary
|
||||
])
|
||||
, nil)!
|
||||
let signatureAlgorithm: SecKeyAlgorithm
|
||||
switch secret.keySize {
|
||||
case 256:
|
||||
signatureAlgorithm = .ecdsaSignatureMessageX962SHA256
|
||||
case 384:
|
||||
signatureAlgorithm = .ecdsaSignatureMessageX962SHA384
|
||||
default:
|
||||
fatalError()
|
||||
return SecKeyCreateSignature(privateKey, signatureAlgorithm(for: secret), data as CFData, nil)! as Data
|
||||
}
|
||||
|
||||
public func verify(signature: Data, for data: Data, with secret: Stub.Secret) throws -> Bool {
|
||||
let attributes = KeychainDictionary([
|
||||
kSecAttrKeyType: secret.algorithm.secAttrKeyType,
|
||||
kSecAttrKeySizeInBits: secret.keySize,
|
||||
kSecAttrKeyClass: kSecAttrKeyClassPublic
|
||||
])
|
||||
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)
|
||||
}
|
||||
return SecKeyCreateSignature(privateKey, signatureAlgorithm, data as CFData, nil)! as Data
|
||||
let key = untypedSafe as! SecKey
|
||||
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? {
|
||||
@ -78,6 +91,9 @@ extension Stub {
|
||||
public func persistAuthentication(secret: Stub.Secret, forDuration duration: TimeInterval) throws {
|
||||
}
|
||||
|
||||
public func reloadSecrets() {
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
}
|
||||
|
@ -1,19 +1,19 @@
|
||||
import Foundation
|
||||
import XCTest
|
||||
import Testing
|
||||
@testable import SecretKit
|
||||
@testable import SecureEnclaveSecretKit
|
||||
@testable import SmartCardSecretKit
|
||||
|
||||
class AnySecretTests: XCTestCase {
|
||||
@Suite struct AnySecretTests {
|
||||
|
||||
func testEraser() {
|
||||
@Test func eraser() {
|
||||
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)
|
||||
XCTAssert(erased.id == secret.id as AnyHashable)
|
||||
XCTAssert(erased.name == secret.name)
|
||||
XCTAssert(erased.algorithm == secret.algorithm)
|
||||
XCTAssert(erased.keySize == secret.keySize)
|
||||
XCTAssert(erased.publicKey == secret.publicKey)
|
||||
#expect(erased.id == secret.id as AnyHashable)
|
||||
#expect(erased.name == secret.name)
|
||||
#expect(erased.algorithm == secret.algorithm)
|
||||
#expect(erased.keySize == secret.keySize)
|
||||
#expect(erased.publicKey == secret.publicKey)
|
||||
}
|
||||
|
||||
}
|
||||
|
@ -1,19 +1,19 @@
|
||||
import Foundation
|
||||
import XCTest
|
||||
import Testing
|
||||
@testable import SecretKit
|
||||
@testable import SecureEnclaveSecretKit
|
||||
@testable import SmartCardSecretKit
|
||||
|
||||
class OpenSSHReaderTests: XCTestCase {
|
||||
@Suite struct OpenSSHReaderTests {
|
||||
|
||||
func testSignatureRequest() {
|
||||
@Test func signatureRequest() {
|
||||
let reader = OpenSSHReader(data: Constants.signatureRequest)
|
||||
let hash = reader.readNextChunk()
|
||||
XCTAssert(hash == Data(base64Encoded: "AAAAE2VjZHNhLXNoYTItbmlzdHAzODQAAAAIbmlzdHAzODQAAABhBEqCbkJbOHy5S1wVCaJoKPmpS0egM4frMqllgnlRRQ/Uvnn6EVS8oV03cPA2Bz0EdESyRKA/sbmn0aBtgjIwGELxu45UXEW1TEz6TxyS0u3vuIqR3Wo1CrQWRDnkrG/pBQ=="))
|
||||
#expect(hash == Data(base64Encoded: "AAAAE2VjZHNhLXNoYTItbmlzdHAzODQAAAAIbmlzdHAzODQAAABhBEqCbkJbOHy5S1wVCaJoKPmpS0egM4frMqllgnlRRQ/Uvnn6EVS8oV03cPA2Bz0EdESyRKA/sbmn0aBtgjIwGELxu45UXEW1TEz6TxyS0u3vuIqR3Wo1CrQWRDnkrG/pBQ=="))
|
||||
let dataToSign = reader.readNextChunk()
|
||||
XCTAssert(dataToSign == Data(base64Encoded: "AAAAICi5xf1ixOestUlxdjvt/BDcM+rzhwy7Vo8cW5YcxA8+MgAAAANnaXQAAAAOc3NoLWNvbm5lY3Rpb24AAAAJcHVibGlja2V5AQAAABNlY2RzYS1zaGEyLW5pc3RwMzg0AAAAiAAAABNlY2RzYS1zaGEyLW5pc3RwMzg0AAAACG5pc3RwMzg0AAAAYQRKgm5CWzh8uUtcFQmiaCj5qUtHoDOH6zKpZYJ5UUUP1L55+hFUvKFdN3DwNgc9BHREskSgP7G5p9GgbYIyMBhC8buOVFxFtUxM+k8cktLt77iKkd1qNQq0FkQ55Kxv6QU="))
|
||||
#expect(dataToSign == Data(base64Encoded: "AAAAICi5xf1ixOestUlxdjvt/BDcM+rzhwy7Vo8cW5YcxA8+MgAAAANnaXQAAAAOc3NoLWNvbm5lY3Rpb24AAAAJcHVibGlja2V5AQAAABNlY2RzYS1zaGEyLW5pc3RwMzg0AAAAiAAAABNlY2RzYS1zaGEyLW5pc3RwMzg0AAAACG5pc3RwMzg0AAAAYQRKgm5CWzh8uUtcFQmiaCj5qUtHoDOH6zKpZYJ5UUUP1L55+hFUvKFdN3DwNgc9BHREskSgP7G5p9GgbYIyMBhC8buOVFxFtUxM+k8cktLt77iKkd1qNQq0FkQ55Kxv6QU="))
|
||||
let empty = reader.readNextChunk()
|
||||
XCTAssert(empty.isEmpty)
|
||||
#expect(empty.isEmpty)
|
||||
}
|
||||
|
||||
}
|
||||
|
@ -1,45 +1,45 @@
|
||||
import Foundation
|
||||
import XCTest
|
||||
import Testing
|
||||
@testable import SecretKit
|
||||
@testable import SecureEnclaveSecretKit
|
||||
@testable import SmartCardSecretKit
|
||||
|
||||
class OpenSSHWriterTests: XCTestCase {
|
||||
@Suite struct OpenSSHWriterTests {
|
||||
|
||||
let writer = OpenSSHKeyWriter()
|
||||
|
||||
func testECDSA256MD5Fingerprint() {
|
||||
XCTAssertEqual(writer.openSSHMD5Fingerprint(secret: Constants.ecdsa256Secret), "dc:60:4d:ff:c2:d9:18:8b:2f:24:40:b5:7f:43:47:e5")
|
||||
@Test func ecdsa256MD5Fingerprint() {
|
||||
#expect(writer.openSSHMD5Fingerprint(secret: Constants.ecdsa256Secret) == "dc:60:4d:ff:c2:d9:18:8b:2f:24:40:b5:7f:43:47:e5")
|
||||
}
|
||||
|
||||
func testECDSA256SHA256Fingerprint() {
|
||||
XCTAssertEqual(writer.openSSHSHA256Fingerprint(secret: Constants.ecdsa256Secret), "SHA256:/VQFeGyM8qKA8rB6WGMuZZxZLJln2UgXLk3F0uTF650")
|
||||
@Test func ecdsa256SHA256Fingerprint() {
|
||||
#expect(writer.openSSHSHA256Fingerprint(secret: Constants.ecdsa256Secret) == "SHA256:/VQFeGyM8qKA8rB6WGMuZZxZLJln2UgXLk3F0uTF650")
|
||||
}
|
||||
|
||||
func testECDSA256PublicKey() {
|
||||
XCTAssertEqual(writer.openSSHString(secret: Constants.ecdsa256Secret),
|
||||
@Test func ecdsa256PublicKey() {
|
||||
#expect(writer.openSSHString(secret: Constants.ecdsa256Secret) ==
|
||||
"ecdsa-sha2-nistp256 AAAAE2VjZHNhLXNoYTItbmlzdHAyNTYAAAAIbmlzdHAyNTYAAABBBOVEjgAA5PHqRgwykjN5qM21uWCHFSY/Sqo5gkHAkn+e1MMQKHOLga7ucB9b3mif33MBid59GRK9GEPVlMiSQwo=")
|
||||
}
|
||||
|
||||
func testECDSA256Hash() {
|
||||
XCTAssertEqual(writer.data(secret: Constants.ecdsa256Secret), Data(base64Encoded: "AAAAE2VjZHNhLXNoYTItbmlzdHAyNTYAAAAIbmlzdHAyNTYAAABBBOVEjgAA5PHqRgwykjN5qM21uWCHFSY/Sqo5gkHAkn+e1MMQKHOLga7ucB9b3mif33MBid59GRK9GEPVlMiSQwo="))
|
||||
@Test func ecdsa256Hash() {
|
||||
#expect(writer.data(secret: Constants.ecdsa256Secret) == Data(base64Encoded: "AAAAE2VjZHNhLXNoYTItbmlzdHAyNTYAAAAIbmlzdHAyNTYAAABBBOVEjgAA5PHqRgwykjN5qM21uWCHFSY/Sqo5gkHAkn+e1MMQKHOLga7ucB9b3mif33MBid59GRK9GEPVlMiSQwo="))
|
||||
}
|
||||
|
||||
func testECDSA384MD5Fingerprint() {
|
||||
XCTAssertEqual(writer.openSSHMD5Fingerprint(secret: Constants.ecdsa384Secret), "66:e0:66:d7:41:ed:19:8e:e2:20:df:ce:ac:7e:2b:6e")
|
||||
@Test func ecdsa384MD5Fingerprint() {
|
||||
#expect(writer.openSSHMD5Fingerprint(secret: Constants.ecdsa384Secret) == "66:e0:66:d7:41:ed:19:8e:e2:20:df:ce:ac:7e:2b:6e")
|
||||
}
|
||||
|
||||
func testECDSA384SHA256Fingerprint() {
|
||||
XCTAssertEqual(writer.openSSHSHA256Fingerprint(secret: Constants.ecdsa384Secret), "SHA256:GJUEymQNL9ymaMRRJCMGY4rWIJHu/Lm8Yhao/PAiz1I")
|
||||
@Test func ecdsa384SHA256Fingerprint() {
|
||||
#expect(writer.openSSHSHA256Fingerprint(secret: Constants.ecdsa384Secret) == "SHA256:GJUEymQNL9ymaMRRJCMGY4rWIJHu/Lm8Yhao/PAiz1I")
|
||||
}
|
||||
|
||||
func testECDSA384PublicKey() {
|
||||
XCTAssertEqual(writer.openSSHString(secret: Constants.ecdsa384Secret),
|
||||
@Test func ecdsa384PublicKey() {
|
||||
#expect(writer.openSSHString(secret: Constants.ecdsa384Secret) ==
|
||||
"ecdsa-sha2-nistp384 AAAAE2VjZHNhLXNoYTItbmlzdHAzODQAAAAIbmlzdHAzODQAAABhBG2MNc/C5OTHFE2tBvbZCVcpOGa8vBMquiTLkH4lwkeqOPxhi+PyYUfQZMTRJNPiTyWPoMBqNiCIFRVv60yPN/AHufHaOgbdTP42EgMlMMImkAjYUEv9DESHTVIs2PW1yQ==")
|
||||
}
|
||||
|
||||
func testECDSA384Hash() {
|
||||
XCTAssertEqual(writer.data(secret: Constants.ecdsa384Secret), Data(base64Encoded: "AAAAE2VjZHNhLXNoYTItbmlzdHAzODQAAAAIbmlzdHAzODQAAABhBG2MNc/C5OTHFE2tBvbZCVcpOGa8vBMquiTLkH4lwkeqOPxhi+PyYUfQZMTRJNPiTyWPoMBqNiCIFRVv60yPN/AHufHaOgbdTP42EgMlMMImkAjYUEv9DESHTVIs2PW1yQ=="))
|
||||
@Test func ecdsa384Hash() {
|
||||
#expect(writer.data(secret: Constants.ecdsa384Secret) == Data(base64Encoded: "AAAAE2VjZHNhLXNoYTItbmlzdHAzODQAAAAIbmlzdHAzODQAAABhBG2MNc/C5OTHFE2tBvbZCVcpOGa8vBMquiTLkH4lwkeqOPxhi+PyYUfQZMTRJNPiTyWPoMBqNiCIFRVv60yPN/AHufHaOgbdTP42EgMlMMImkAjYUEv9DESHTVIs2PW1yQ=="))
|
||||
}
|
||||
|
||||
}
|
||||
|
@ -6,8 +6,9 @@ import SecureEnclaveSecretKit
|
||||
import SmartCardSecretKit
|
||||
import SecretAgentKit
|
||||
import Brief
|
||||
import Observation
|
||||
|
||||
@NSApplicationMain
|
||||
@main
|
||||
class AppDelegate: NSObject, NSApplicationDelegate {
|
||||
|
||||
private let storeList: SecretStoreList = {
|
||||
@ -27,22 +28,32 @@ class AppDelegate: NSObject, NSApplicationDelegate {
|
||||
return SocketController(path: path)
|
||||
}()
|
||||
private var updateSink: AnyCancellable?
|
||||
private let logger = Logger(subsystem: "com.maxgoedjen.secretive.secretagent", category: "AppDelegate")
|
||||
|
||||
func applicationDidFinishLaunching(_ aNotification: Notification) {
|
||||
Logger().debug("SecretAgent finished launching")
|
||||
DispatchQueue.main.async {
|
||||
self.socketController.handler = self.agent.handle(reader:writer:)
|
||||
logger.debug("SecretAgent finished launching")
|
||||
Task { @MainActor in
|
||||
socketController.handler = { [agent] reader, writer in
|
||||
await agent.handle(reader: reader, writer: writer)
|
||||
}
|
||||
}
|
||||
NotificationCenter.default.addObserver(forName: .secretStoreReloaded, object: nil, queue: .main) { [self] _ in
|
||||
try? publicKeyFileStoreController.generatePublicKeys(for: storeList.stores.flatMap({ $0.secrets }), clear: true)
|
||||
Task {
|
||||
for await _ in NotificationCenter.default.notifications(named: .secretStoreReloaded) {
|
||||
try? publicKeyFileStoreController.generatePublicKeys(for: storeList.allSecrets, clear: true)
|
||||
}
|
||||
}
|
||||
try? publicKeyFileStoreController.generatePublicKeys(for: storeList.stores.flatMap({ $0.secrets }), clear: true)
|
||||
try? publicKeyFileStoreController.generatePublicKeys(for: storeList.allSecrets, clear: true)
|
||||
notifier.prompt()
|
||||
updateSink = updater.$update.sink { update in
|
||||
guard let update = update else { return }
|
||||
self.notifier.notify(update: update, ignore: self.updater.ignore(release:))
|
||||
_ = withObservationTracking {
|
||||
updater.update
|
||||
} onChange: { [updater, notifier] in
|
||||
notifier.notify(update: updater.update!) { release in
|
||||
Task {
|
||||
await updater.ignore(release: release)
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
}
|
||||
|
||||
|
@ -4,14 +4,15 @@ import AppKit
|
||||
import SecretKit
|
||||
import SecretAgentKit
|
||||
import Brief
|
||||
import Synchronization
|
||||
|
||||
class Notifier {
|
||||
final class Notifier: Sendable {
|
||||
|
||||
private let notificationDelegate = NotificationDelegate()
|
||||
|
||||
init() {
|
||||
let updateAction = UNNotificationAction(identifier: Constants.updateActionIdentitifier, title: "Update", options: [])
|
||||
let ignoreAction = UNNotificationAction(identifier: Constants.ignoreActionIdentitifier, title: "Ignore", options: [])
|
||||
let updateAction = UNNotificationAction(identifier: Constants.updateActionIdentitifier, title: String(localized: "update_notification_update_button"), options: [])
|
||||
let ignoreAction = UNNotificationAction(identifier: Constants.ignoreActionIdentitifier, title: String(localized: "update_notification_ignore_button"), options: [])
|
||||
let updateCategory = UNNotificationCategory(identifier: Constants.updateCategoryIdentitifier, actions: [updateAction, ignoreAction], intentIdentifiers: [], options: [])
|
||||
let criticalUpdateCategory = UNNotificationCategory(identifier: Constants.criticalUpdateCategoryIdentitifier, actions: [updateAction], intentIdentifiers: [], options: [])
|
||||
|
||||
@ -22,7 +23,7 @@ class Notifier {
|
||||
Measurement(value: 24, unit: UnitDuration.hours)
|
||||
]
|
||||
|
||||
let doNotPersistAction = UNNotificationAction(identifier: Constants.doNotPersistActionIdentitifier, title: "Do Not Unlock", options: [])
|
||||
let doNotPersistAction = UNNotificationAction(identifier: Constants.doNotPersistActionIdentitifier, title: String(localized: "persist_authentication_decline_button"), options: [])
|
||||
var allPersistenceActions = [doNotPersistAction]
|
||||
|
||||
let formatter = DateComponentsFormatter()
|
||||
@ -34,20 +35,24 @@ class Notifier {
|
||||
guard let string = formatter.string(from: seconds)?.capitalized else { continue }
|
||||
let identifier = Constants.persistAuthenticationCategoryIdentitifier.appending("\(seconds)")
|
||||
let action = UNNotificationAction(identifier: identifier, title: string, options: [])
|
||||
notificationDelegate.persistOptions[identifier] = seconds
|
||||
notificationDelegate.state.withLock { state in
|
||||
state.persistOptions[identifier] = seconds
|
||||
}
|
||||
allPersistenceActions.append(action)
|
||||
}
|
||||
|
||||
let persistAuthenticationCategory = UNNotificationCategory(identifier: Constants.persistAuthenticationCategoryIdentitifier, actions: allPersistenceActions, intentIdentifiers: [], options: [])
|
||||
if persistAuthenticationCategory.responds(to: Selector(("actionsMenuTitle"))) {
|
||||
persistAuthenticationCategory.setValue("Leave Unlocked", forKey: "_actionsMenuTitle")
|
||||
persistAuthenticationCategory.setValue(String(localized: "persist_authentication_accept_button"), forKey: "_actionsMenuTitle")
|
||||
}
|
||||
UNUserNotificationCenter.current().setNotificationCategories([updateCategory, criticalUpdateCategory, persistAuthenticationCategory])
|
||||
UNUserNotificationCenter.current().delegate = notificationDelegate
|
||||
|
||||
notificationDelegate.persistAuthentication = { secret, store, duration in
|
||||
guard let duration = duration else { return }
|
||||
try? store.persistAuthentication(secret: secret, forDuration: duration)
|
||||
notificationDelegate.state.withLock { state in
|
||||
state.persistAuthentication = { secret, store, duration in
|
||||
guard let duration = duration else { return }
|
||||
try? await store.persistAuthentication(secret: secret, forDuration: duration)
|
||||
}
|
||||
}
|
||||
|
||||
}
|
||||
@ -57,42 +62,42 @@ class Notifier {
|
||||
notificationCenter.requestAuthorization(options: .alert) { _, _ in }
|
||||
}
|
||||
|
||||
func notify(accessTo secret: AnySecret, from store: AnySecretStore, by provenance: SigningRequestProvenance) {
|
||||
notificationDelegate.pendingPersistableSecrets[secret.id.description] = secret
|
||||
notificationDelegate.pendingPersistableStores[store.id.description] = store
|
||||
func notify(accessTo secret: AnySecret, from store: AnySecretStore, by provenance: SigningRequestProvenance) async {
|
||||
notificationDelegate.state.withLock { state in
|
||||
state.pendingPersistableSecrets[secret.id.description] = secret
|
||||
state.pendingPersistableStores[store.id.description] = store
|
||||
}
|
||||
let notificationCenter = UNUserNotificationCenter.current()
|
||||
let notificationContent = UNMutableNotificationContent()
|
||||
notificationContent.title = "Signed Request from \(provenance.origin.displayName)"
|
||||
notificationContent.subtitle = "Using secret \"\(secret.name)\""
|
||||
notificationContent.title = String(localized: "signed_notification_title_\(provenance.origin.displayName)")
|
||||
notificationContent.subtitle = String(localized: "signed_notification_description_\(secret.name)")
|
||||
notificationContent.userInfo[Constants.persistSecretIDKey] = secret.id.description
|
||||
notificationContent.userInfo[Constants.persistStoreIDKey] = store.id.description
|
||||
if #available(macOS 12.0, *) {
|
||||
notificationContent.interruptionLevel = .timeSensitive
|
||||
}
|
||||
if secret.requiresAuthentication && store.existingPersistedAuthenticationContext(secret: secret) == nil {
|
||||
notificationContent.interruptionLevel = .timeSensitive
|
||||
if await store.existingPersistedAuthenticationContext(secret: secret) == nil && secret.requiresAuthentication {
|
||||
notificationContent.categoryIdentifier = Constants.persistAuthenticationCategoryIdentitifier
|
||||
}
|
||||
if let iconURL = provenance.origin.iconURL, let attachment = try? UNNotificationAttachment(identifier: "icon", url: iconURL, options: nil) {
|
||||
notificationContent.attachments = [attachment]
|
||||
}
|
||||
let request = UNNotificationRequest(identifier: UUID().uuidString, content: notificationContent, trigger: nil)
|
||||
notificationCenter.add(request, withCompletionHandler: nil)
|
||||
try? await notificationCenter.add(request)
|
||||
}
|
||||
|
||||
func notify(update: Release, ignore: ((Release) -> Void)?) {
|
||||
notificationDelegate.release = update
|
||||
notificationDelegate.ignore = ignore
|
||||
notificationDelegate.state.withLock { [update] state in
|
||||
state.release = update
|
||||
// state.ignore = ignore
|
||||
}
|
||||
let notificationCenter = UNUserNotificationCenter.current()
|
||||
let notificationContent = UNMutableNotificationContent()
|
||||
if update.critical {
|
||||
if #available(macOS 12.0, *) {
|
||||
notificationContent.interruptionLevel = .critical
|
||||
}
|
||||
notificationContent.title = "Critical Security Update - \(update.name)"
|
||||
notificationContent.interruptionLevel = .critical
|
||||
notificationContent.title = String(localized: "update_notification_update_critical_title_\(update.name)")
|
||||
} else {
|
||||
notificationContent.title = "Update Available - \(update.name)"
|
||||
notificationContent.title = String(localized: "update_notification_update_normal_title_\(update.name)")
|
||||
}
|
||||
notificationContent.subtitle = "Click to Update"
|
||||
notificationContent.subtitle = String(localized: "update_notification_update_description")
|
||||
notificationContent.body = update.body
|
||||
notificationContent.categoryIdentifier = update.critical ? Constants.criticalUpdateCategoryIdentitifier : Constants.updateCategoryIdentitifier
|
||||
let request = UNNotificationRequest(identifier: UUID().uuidString, content: notificationContent, trigger: nil)
|
||||
@ -103,11 +108,11 @@ class Notifier {
|
||||
|
||||
extension Notifier: SigningWitness {
|
||||
|
||||
func speakNowOrForeverHoldYourPeace(forAccessTo secret: AnySecret, from store: AnySecretStore, by provenance: SigningRequestProvenance) throws {
|
||||
func speakNowOrForeverHoldYourPeace(forAccessTo secret: AnySecret, from store: AnySecretStore, by provenance: SigningRequestProvenance) async throws {
|
||||
}
|
||||
|
||||
func witness(accessTo secret: AnySecret, from store: AnySecretStore, by provenance: SigningRequestProvenance) throws {
|
||||
notify(accessTo: secret, from: store, by: provenance)
|
||||
func witness(accessTo secret: AnySecret, from store: AnySecretStore, by provenance: SigningRequestProvenance) async throws {
|
||||
await notify(accessTo: secret, from: store, by: provenance)
|
||||
}
|
||||
|
||||
}
|
||||
@ -133,55 +138,66 @@ extension Notifier {
|
||||
|
||||
}
|
||||
|
||||
class NotificationDelegate: NSObject, UNUserNotificationCenterDelegate {
|
||||
|
||||
fileprivate var release: Release?
|
||||
fileprivate var ignore: ((Release) -> Void)?
|
||||
fileprivate var persistAuthentication: ((AnySecret, AnySecretStore, TimeInterval?) -> Void)?
|
||||
fileprivate var persistOptions: [String: TimeInterval] = [:]
|
||||
fileprivate var pendingPersistableStores: [String: AnySecretStore] = [:]
|
||||
fileprivate var pendingPersistableSecrets: [String: AnySecret] = [:]
|
||||
final class NotificationDelegate: NSObject, UNUserNotificationCenterDelegate, Sendable {
|
||||
|
||||
struct State {
|
||||
typealias PersistAuthentication = ((AnySecret, AnySecretStore, TimeInterval?) async -> Void)
|
||||
typealias Ignore = ((Release) -> Void)
|
||||
fileprivate var release: Release?
|
||||
fileprivate var ignore: Ignore?
|
||||
fileprivate var persistAuthentication: PersistAuthentication?
|
||||
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, didReceive response: UNNotificationResponse, withCompletionHandler completionHandler: @escaping () -> Void) {
|
||||
|
||||
func userNotificationCenter(_ center: UNUserNotificationCenter, didReceive response: UNNotificationResponse) async {
|
||||
let category = response.notification.request.content.categoryIdentifier
|
||||
switch category {
|
||||
case Notifier.Constants.updateCategoryIdentitifier:
|
||||
handleUpdateResponse(response: response)
|
||||
case Notifier.Constants.persistAuthenticationCategoryIdentitifier:
|
||||
handlePersistAuthenticationResponse(response: response)
|
||||
await handlePersistAuthenticationResponse(response: response)
|
||||
default:
|
||||
fatalError()
|
||||
break
|
||||
}
|
||||
|
||||
completionHandler()
|
||||
}
|
||||
|
||||
func handleUpdateResponse(response: UNNotificationResponse) {
|
||||
guard let update = release else { return }
|
||||
switch response.actionIdentifier {
|
||||
case Notifier.Constants.updateActionIdentitifier, UNNotificationDefaultActionIdentifier:
|
||||
NSWorkspace.shared.open(update.html_url)
|
||||
case Notifier.Constants.ignoreActionIdentitifier:
|
||||
ignore?(update)
|
||||
default:
|
||||
fatalError()
|
||||
state.withLock { state in
|
||||
guard let update = state.release else { return }
|
||||
switch response.actionIdentifier {
|
||||
case Notifier.Constants.updateActionIdentitifier, UNNotificationDefaultActionIdentifier:
|
||||
NSWorkspace.shared.open(update.html_url)
|
||||
case Notifier.Constants.ignoreActionIdentitifier:
|
||||
state.ignore?(update)
|
||||
default:
|
||||
fatalError()
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func handlePersistAuthenticationResponse(response: UNNotificationResponse) {
|
||||
guard let secretID = response.notification.request.content.userInfo[Notifier.Constants.persistSecretIDKey] as? String, let secret = pendingPersistableSecrets[secretID],
|
||||
let storeID = response.notification.request.content.userInfo[Notifier.Constants.persistStoreIDKey] as? String, let store = pendingPersistableStores[storeID]
|
||||
else { return }
|
||||
pendingPersistableSecrets[secretID] = nil
|
||||
persistAuthentication?(secret, store, persistOptions[response.actionIdentifier])
|
||||
func handlePersistAuthenticationResponse(response: UNNotificationResponse) async {
|
||||
// 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 = state.pendingPersistableSecrets[secretID],
|
||||
// let storeID = response.notification.request.content.userInfo[Notifier.Constants.persistStoreIDKey] as? String, let store = state.pendingPersistableStores[storeID]
|
||||
// else { return (nil, nil, nil, nil) }
|
||||
// state.pendingPersistableSecrets[secretID] = nil
|
||||
// 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) {
|
||||
completionHandler([.list, .banner])
|
||||
|
||||
func userNotificationCenter(_ center: UNUserNotificationCenter, willPresent notification: UNNotification) async -> UNNotificationPresentationOptions {
|
||||
[.list, .banner]
|
||||
}
|
||||
|
||||
}
|
||||
|
@ -3,7 +3,7 @@
|
||||
archiveVersion = 1;
|
||||
classes = {
|
||||
};
|
||||
objectVersion = 52;
|
||||
objectVersion = 54;
|
||||
objects = {
|
||||
|
||||
/* Begin PBXBuildFile section */
|
||||
@ -18,6 +18,7 @@
|
||||
5003EF612780081600DF2006 /* SmartCardSecretKit in Frameworks */ = {isa = PBXBuildFile; productRef = 5003EF602780081600DF2006 /* SmartCardSecretKit */; };
|
||||
5003EF632780081B00DF2006 /* SecureEnclaveSecretKit in Frameworks */ = {isa = PBXBuildFile; productRef = 5003EF622780081B00DF2006 /* SecureEnclaveSecretKit */; };
|
||||
5003EF652780081B00DF2006 /* SmartCardSecretKit in Frameworks */ = {isa = PBXBuildFile; productRef = 5003EF642780081B00DF2006 /* SmartCardSecretKit */; };
|
||||
500B93C32B478D8400E157DE /* Localizable.xcstrings in Resources */ = {isa = PBXBuildFile; fileRef = 500B93C22B478D8400E157DE /* Localizable.xcstrings */; };
|
||||
501421622781262300BBAA70 /* Brief in Frameworks */ = {isa = PBXBuildFile; productRef = 501421612781262300BBAA70 /* Brief */; };
|
||||
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 */; };
|
||||
@ -29,8 +30,8 @@
|
||||
50617D8523FCE48E0099B055 /* ContentView.swift in Sources */ = {isa = PBXBuildFile; fileRef = 50617D8423FCE48E0099B055 /* ContentView.swift */; };
|
||||
50617D8723FCE48E0099B055 /* Assets.xcassets in Resources */ = {isa = PBXBuildFile; fileRef = 50617D8623FCE48E0099B055 /* 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 */; };
|
||||
5065E313295517C500E16645 /* ToolbarButtonStyle.swift in Sources */ = {isa = PBXBuildFile; fileRef = 5065E312295517C500E16645 /* ToolbarButtonStyle.swift */; };
|
||||
5066A6C22516F303004B5A36 /* SetupView.swift in Sources */ = {isa = PBXBuildFile; fileRef = 5066A6C12516F303004B5A36 /* SetupView.swift */; };
|
||||
5066A6C82516FE6E004B5A36 /* CopyableView.swift in Sources */ = {isa = PBXBuildFile; fileRef = 5066A6C72516FE6E004B5A36 /* CopyableView.swift */; };
|
||||
5066A6F7251829B1004B5A36 /* ShellConfigurationController.swift in Sources */ = {isa = PBXBuildFile; fileRef = 5066A6F6251829B1004B5A36 /* ShellConfigurationController.swift */; };
|
||||
@ -50,6 +51,7 @@
|
||||
50B8550D24138C4F009958AC /* DeleteSecretView.swift in Sources */ = {isa = PBXBuildFile; fileRef = 50B8550C24138C4F009958AC /* DeleteSecretView.swift */; };
|
||||
50BB046B2418AAAE00D6E079 /* EmptyStoreView.swift in Sources */ = {isa = PBXBuildFile; fileRef = 50BB046A2418AAAE00D6E079 /* EmptyStoreView.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 */
|
||||
|
||||
/* Begin PBXContainerItemProxy section */
|
||||
@ -60,13 +62,6 @@
|
||||
remoteGlobalIDString = 50A3B78924026B7500D209EA;
|
||||
remoteInfo = SecretAgent;
|
||||
};
|
||||
50617D9523FCE48E0099B055 /* PBXContainerItemProxy */ = {
|
||||
isa = PBXContainerItemProxy;
|
||||
containerPortal = 50617D7723FCE48D0099B055 /* Project object */;
|
||||
proxyType = 1;
|
||||
remoteGlobalIDString = 50617D7E23FCE48D0099B055;
|
||||
remoteInfo = Secretive;
|
||||
};
|
||||
/* End PBXContainerItemProxy section */
|
||||
|
||||
/* Begin PBXCopyFilesBuildPhase section */
|
||||
@ -107,6 +102,7 @@
|
||||
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>"; };
|
||||
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>"; };
|
||||
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>"; };
|
||||
@ -119,10 +115,8 @@
|
||||
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>"; };
|
||||
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>"; };
|
||||
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>"; };
|
||||
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>"; };
|
||||
@ -161,13 +155,6 @@
|
||||
);
|
||||
runOnlyForDeploymentPostprocessing = 0;
|
||||
};
|
||||
50617D9123FCE48E0099B055 /* Frameworks */ = {
|
||||
isa = PBXFrameworksBuildPhase;
|
||||
buildActionMask = 2147483647;
|
||||
files = (
|
||||
);
|
||||
runOnlyForDeploymentPostprocessing = 0;
|
||||
};
|
||||
50A3B78724026B7500D209EA /* Frameworks */ = {
|
||||
isa = PBXFrameworksBuildPhase;
|
||||
buildActionMask = 2147483647;
|
||||
@ -196,7 +183,6 @@
|
||||
children = (
|
||||
5003EF39278005C800DF2006 /* Packages */,
|
||||
50617D8123FCE48E0099B055 /* Secretive */,
|
||||
50617D9723FCE48E0099B055 /* SecretiveTests */,
|
||||
50A3B78B24026B7500D209EA /* SecretAgent */,
|
||||
508A58AF241E144C0069DC07 /* Config */,
|
||||
50617D8023FCE48E0099B055 /* Products */,
|
||||
@ -208,7 +194,6 @@
|
||||
isa = PBXGroup;
|
||||
children = (
|
||||
50617D7F23FCE48E0099B055 /* Secretive.app */,
|
||||
50617D9423FCE48E0099B055 /* SecretiveTests.xctest */,
|
||||
50A3B78A24026B7500D209EA /* SecretAgent.app */,
|
||||
);
|
||||
name = Products;
|
||||
@ -226,6 +211,7 @@
|
||||
508BF28D25B4F005009EFB7E /* InternetAccessPolicy.plist */,
|
||||
50617D8F23FCE48E0099B055 /* Secretive.entitlements */,
|
||||
506772C62424784600034DED /* Credits.rtf */,
|
||||
500B93C22B478D8400E157DE /* Localizable.xcstrings */,
|
||||
50617D8823FCE48E0099B055 /* Preview Content */,
|
||||
);
|
||||
path = Secretive;
|
||||
@ -242,15 +228,6 @@
|
||||
path = "Preview Content";
|
||||
sourceTree = "<group>";
|
||||
};
|
||||
50617D9723FCE48E0099B055 /* SecretiveTests */ = {
|
||||
isa = PBXGroup;
|
||||
children = (
|
||||
50617D9823FCE48E0099B055 /* SecretiveTests.swift */,
|
||||
50617D9A23FCE48E0099B055 /* Info.plist */,
|
||||
);
|
||||
path = SecretiveTests;
|
||||
sourceTree = "<group>";
|
||||
};
|
||||
508A58AF241E144C0069DC07 /* Config */ = {
|
||||
isa = PBXGroup;
|
||||
children = (
|
||||
@ -264,6 +241,7 @@
|
||||
isa = PBXGroup;
|
||||
children = (
|
||||
50617D8423FCE48E0099B055 /* ContentView.swift */,
|
||||
5065E312295517C500E16645 /* ToolbarButtonStyle.swift */,
|
||||
5079BA0E250F29BF00EA86F4 /* StoreListView.swift */,
|
||||
50153E21250DECA300525160 /* SecretListItemView.swift */,
|
||||
50C385A42407A76D00AF2719 /* SecretDetailView.swift */,
|
||||
@ -350,24 +328,6 @@
|
||||
productReference = 50617D7F23FCE48E0099B055 /* Secretive.app */;
|
||||
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";
|
||||
};
|
||||
50A3B78924026B7500D209EA /* SecretAgent */ = {
|
||||
isa = PBXNativeTarget;
|
||||
buildConfigurationList = 50A3B79A24026B7600D209EA /* Build configuration list for PBXNativeTarget "SecretAgent" */;
|
||||
@ -406,10 +366,6 @@
|
||||
50617D7E23FCE48D0099B055 = {
|
||||
CreatedOnToolsVersion = 11.3;
|
||||
};
|
||||
50617D9323FCE48E0099B055 = {
|
||||
CreatedOnToolsVersion = 11.3;
|
||||
TestTargetID = 50617D7E23FCE48D0099B055;
|
||||
};
|
||||
50A3B78924026B7500D209EA = {
|
||||
CreatedOnToolsVersion = 11.4;
|
||||
};
|
||||
@ -422,6 +378,13 @@
|
||||
knownRegions = (
|
||||
en,
|
||||
Base,
|
||||
it,
|
||||
fr,
|
||||
de,
|
||||
"pt-BR",
|
||||
fi,
|
||||
ko,
|
||||
ca,
|
||||
);
|
||||
mainGroup = 50617D7623FCE48D0099B055;
|
||||
productRefGroup = 50617D8023FCE48E0099B055 /* Products */;
|
||||
@ -429,7 +392,6 @@
|
||||
projectRoot = "";
|
||||
targets = (
|
||||
50617D7E23FCE48D0099B055 /* Secretive */,
|
||||
50617D9323FCE48E0099B055 /* SecretiveTests */,
|
||||
50A3B78924026B7500D209EA /* SecretAgent */,
|
||||
);
|
||||
};
|
||||
@ -441,24 +403,19 @@
|
||||
buildActionMask = 2147483647;
|
||||
files = (
|
||||
50617D8A23FCE48E0099B055 /* Preview Assets.xcassets in Resources */,
|
||||
500B93C32B478D8400E157DE /* Localizable.xcstrings in Resources */,
|
||||
50617D8723FCE48E0099B055 /* Assets.xcassets in Resources */,
|
||||
506772C72424784600034DED /* Credits.rtf in Resources */,
|
||||
508BF28E25B4F005009EFB7E /* InternetAccessPolicy.plist in Resources */,
|
||||
);
|
||||
runOnlyForDeploymentPostprocessing = 0;
|
||||
};
|
||||
50617D9223FCE48E0099B055 /* Resources */ = {
|
||||
isa = PBXResourcesBuildPhase;
|
||||
buildActionMask = 2147483647;
|
||||
files = (
|
||||
);
|
||||
runOnlyForDeploymentPostprocessing = 0;
|
||||
};
|
||||
50A3B78824026B7500D209EA /* Resources */ = {
|
||||
isa = PBXResourcesBuildPhase;
|
||||
buildActionMask = 2147483647;
|
||||
files = (
|
||||
50A3B79724026B7600D209EA /* Main.storyboard in Resources */,
|
||||
50E9CF422B51D596004AB36D /* Localizable.xcstrings in Resources */,
|
||||
50A3B79424026B7600D209EA /* Preview Assets.xcassets in Resources */,
|
||||
50A3B79124026B7600D209EA /* Assets.xcassets in Resources */,
|
||||
508BF2AA25B4F1CB009EFB7E /* InternetAccessPolicy.plist in Resources */,
|
||||
@ -475,6 +432,7 @@
|
||||
2C4A9D2F2636FFD3008CC8E2 /* RenameSecretView.swift in Sources */,
|
||||
5091D2BC25183B830049FD9B /* ApplicationDirectoryController.swift in Sources */,
|
||||
5066A6C22516F303004B5A36 /* SetupView.swift in Sources */,
|
||||
5065E313295517C500E16645 /* ToolbarButtonStyle.swift in Sources */,
|
||||
50617D8523FCE48E0099B055 /* ContentView.swift in Sources */,
|
||||
50571E0324393C2600F76F6C /* JustUpdatedChecker.swift in Sources */,
|
||||
5079BA0F250F29BF00EA86F4 /* StoreListView.swift in Sources */,
|
||||
@ -497,14 +455,6 @@
|
||||
);
|
||||
runOnlyForDeploymentPostprocessing = 0;
|
||||
};
|
||||
50617D9023FCE48E0099B055 /* Sources */ = {
|
||||
isa = PBXSourcesBuildPhase;
|
||||
buildActionMask = 2147483647;
|
||||
files = (
|
||||
50617D9923FCE48E0099B055 /* SecretiveTests.swift in Sources */,
|
||||
);
|
||||
runOnlyForDeploymentPostprocessing = 0;
|
||||
};
|
||||
50A3B78624026B7500D209EA /* Sources */ = {
|
||||
isa = PBXSourcesBuildPhase;
|
||||
buildActionMask = 2147483647;
|
||||
@ -522,11 +472,6 @@
|
||||
target = 50A3B78924026B7500D209EA /* SecretAgent */;
|
||||
targetProxy = 50142166278126B500BBAA70 /* PBXContainerItemProxy */;
|
||||
};
|
||||
50617D9623FCE48E0099B055 /* PBXTargetDependency */ = {
|
||||
isa = PBXTargetDependency;
|
||||
target = 50617D7E23FCE48D0099B055 /* Secretive */;
|
||||
targetProxy = 50617D9523FCE48E0099B055 /* PBXContainerItemProxy */;
|
||||
};
|
||||
/* End PBXTargetDependency section */
|
||||
|
||||
/* Begin PBXVariantGroup section */
|
||||
@ -593,16 +538,18 @@
|
||||
GCC_WARN_UNINITIALIZED_AUTOS = YES_AGGRESSIVE;
|
||||
GCC_WARN_UNUSED_FUNCTION = YES;
|
||||
GCC_WARN_UNUSED_VARIABLE = YES;
|
||||
MACOSX_DEPLOYMENT_TARGET = 11.0;
|
||||
MACOSX_DEPLOYMENT_TARGET = 15.0;
|
||||
MTL_ENABLE_DEBUG_INFO = INCLUDE_SOURCE;
|
||||
MTL_FAST_MATH = YES;
|
||||
ONLY_ACTIVE_ARCH = YES;
|
||||
OTHER_SWIFT_FLAGS = "-Xfrontend -warn-concurrency -Xfrontend -enable-actor-data-race-checks";
|
||||
OTHER_SWIFT_FLAGS = "";
|
||||
SDKROOT = macosx;
|
||||
STRIP_INSTALLED_PRODUCT = NO;
|
||||
STRIP_SWIFT_SYMBOLS = NO;
|
||||
SWIFT_ACTIVE_COMPILATION_CONDITIONS = DEBUG;
|
||||
SWIFT_EMIT_LOC_STRINGS = YES;
|
||||
SWIFT_OPTIMIZATION_LEVEL = "-Onone";
|
||||
SWIFT_VERSION = 6.0;
|
||||
};
|
||||
name = Debug;
|
||||
};
|
||||
@ -652,15 +599,17 @@
|
||||
GCC_WARN_UNINITIALIZED_AUTOS = YES_AGGRESSIVE;
|
||||
GCC_WARN_UNUSED_FUNCTION = YES;
|
||||
GCC_WARN_UNUSED_VARIABLE = YES;
|
||||
MACOSX_DEPLOYMENT_TARGET = 11.0;
|
||||
MACOSX_DEPLOYMENT_TARGET = 15.0;
|
||||
MTL_ENABLE_DEBUG_INFO = NO;
|
||||
MTL_FAST_MATH = YES;
|
||||
OTHER_SWIFT_FLAGS = "-Xfrontend -warn-concurrency -Xfrontend -enable-actor-data-race-checks";
|
||||
OTHER_SWIFT_FLAGS = "";
|
||||
SDKROOT = macosx;
|
||||
STRIP_INSTALLED_PRODUCT = NO;
|
||||
STRIP_SWIFT_SYMBOLS = NO;
|
||||
SWIFT_COMPILATION_MODE = wholemodule;
|
||||
SWIFT_EMIT_LOC_STRINGS = YES;
|
||||
SWIFT_OPTIMIZATION_LEVEL = "-O";
|
||||
SWIFT_VERSION = 6.0;
|
||||
};
|
||||
name = Release;
|
||||
};
|
||||
@ -687,7 +636,6 @@
|
||||
PRODUCT_BUNDLE_IDENTIFIER = com.maxgoedjen.Secretive.Host;
|
||||
PRODUCT_NAME = "$(TARGET_NAME)";
|
||||
PROVISIONING_PROFILE_SPECIFIER = "";
|
||||
SWIFT_VERSION = 5.0;
|
||||
};
|
||||
name = Debug;
|
||||
};
|
||||
@ -714,49 +662,6 @@
|
||||
PRODUCT_BUNDLE_IDENTIFIER = com.maxgoedjen.Secretive.Host;
|
||||
PRODUCT_NAME = "$(TARGET_NAME)";
|
||||
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;
|
||||
};
|
||||
@ -812,16 +717,18 @@
|
||||
GCC_WARN_UNINITIALIZED_AUTOS = YES_AGGRESSIVE;
|
||||
GCC_WARN_UNUSED_FUNCTION = YES;
|
||||
GCC_WARN_UNUSED_VARIABLE = YES;
|
||||
MACOSX_DEPLOYMENT_TARGET = 11.0;
|
||||
MACOSX_DEPLOYMENT_TARGET = 15.0;
|
||||
MTL_ENABLE_DEBUG_INFO = INCLUDE_SOURCE;
|
||||
MTL_FAST_MATH = YES;
|
||||
ONLY_ACTIVE_ARCH = YES;
|
||||
OTHER_SWIFT_FLAGS = "-Xfrontend -warn-concurrency -Xfrontend -enable-actor-data-race-checks";
|
||||
OTHER_SWIFT_FLAGS = "";
|
||||
SDKROOT = macosx;
|
||||
STRIP_INSTALLED_PRODUCT = NO;
|
||||
STRIP_SWIFT_SYMBOLS = NO;
|
||||
SWIFT_ACTIVE_COMPILATION_CONDITIONS = DEBUG;
|
||||
SWIFT_EMIT_LOC_STRINGS = YES;
|
||||
SWIFT_OPTIMIZATION_LEVEL = "-Onone";
|
||||
SWIFT_VERSION = 6.0;
|
||||
};
|
||||
name = Test;
|
||||
};
|
||||
@ -844,29 +751,6 @@
|
||||
MARKETING_VERSION = 1;
|
||||
PRODUCT_BUNDLE_IDENTIFIER = com.maxgoedjen.Secretive.Host;
|
||||
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;
|
||||
};
|
||||
@ -887,7 +771,6 @@
|
||||
MARKETING_VERSION = 1;
|
||||
PRODUCT_BUNDLE_IDENTIFIER = com.maxgoedjen.Secretive.SecretAgent;
|
||||
PRODUCT_NAME = "$(TARGET_NAME)";
|
||||
SWIFT_VERSION = 5.0;
|
||||
};
|
||||
name = Test;
|
||||
};
|
||||
@ -910,7 +793,6 @@
|
||||
MARKETING_VERSION = 1;
|
||||
PRODUCT_BUNDLE_IDENTIFIER = com.maxgoedjen.Secretive.SecretAgent;
|
||||
PRODUCT_NAME = "$(TARGET_NAME)";
|
||||
SWIFT_VERSION = 5.0;
|
||||
};
|
||||
name = Debug;
|
||||
};
|
||||
@ -935,7 +817,6 @@
|
||||
PRODUCT_BUNDLE_IDENTIFIER = com.maxgoedjen.Secretive.SecretAgent;
|
||||
PRODUCT_NAME = "$(TARGET_NAME)";
|
||||
PROVISIONING_PROFILE_SPECIFIER = "Secretive - Secret Agent";
|
||||
SWIFT_VERSION = 5.0;
|
||||
};
|
||||
name = Release;
|
||||
};
|
||||
@ -962,16 +843,6 @@
|
||||
defaultConfigurationIsVisible = 0;
|
||||
defaultConfigurationName = Release;
|
||||
};
|
||||
50617DA023FCE48E0099B055 /* Build configuration list for PBXNativeTarget "SecretiveTests" */ = {
|
||||
isa = XCConfigurationList;
|
||||
buildConfigurations = (
|
||||
50617DA123FCE48E0099B055 /* Debug */,
|
||||
508A5916241EF1A00069DC07 /* Test */,
|
||||
50617DA223FCE48E0099B055 /* Release */,
|
||||
);
|
||||
defaultConfigurationIsVisible = 0;
|
||||
defaultConfigurationName = Release;
|
||||
};
|
||||
50A3B79A24026B7600D209EA /* Build configuration list for PBXNativeTarget "SecretAgent" */ = {
|
||||
isa = XCConfigurationList;
|
||||
buildConfigurations = (
|
||||
|
@ -75,6 +75,7 @@
|
||||
ignoresPersistentStateOnLaunch = "NO"
|
||||
debugDocumentVersioning = "YES"
|
||||
debugServiceExtension = "internal"
|
||||
enableGPUValidationMode = "1"
|
||||
allowLocationSimulation = "YES">
|
||||
<BuildableProductRunnable
|
||||
runnableDebuggingMode = "0">
|
||||
|
@ -5,9 +5,20 @@ import SecureEnclaveSecretKit
|
||||
import SmartCardSecretKit
|
||||
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
|
||||
struct Secretive: App {
|
||||
|
||||
|
||||
private let storeList: SecretStoreList = {
|
||||
let list = SecretStoreList()
|
||||
list.add(store: SecureEnclave.Store())
|
||||
@ -23,10 +34,10 @@ struct Secretive: App {
|
||||
|
||||
@SceneBuilder var body: some Scene {
|
||||
WindowGroup {
|
||||
ContentView<Updater, AgentStatusChecker>(showingCreation: $showingCreation, runningSetup: $showingSetup, hasRunSetup: $hasRunSetup)
|
||||
.environmentObject(storeList)
|
||||
.environmentObject(Updater(checkOnLaunch: hasRunSetup))
|
||||
.environmentObject(agentStatusChecker)
|
||||
ContentView(showingCreation: $showingCreation, runningSetup: $showingSetup, hasRunSetup: $hasRunSetup)
|
||||
.environment(storeList)
|
||||
.environment(Updater(checkOnLaunch: hasRunSetup))
|
||||
.environment(agentStatusChecker)
|
||||
.onAppear {
|
||||
if !hasRunSetup {
|
||||
showingSetup = true
|
||||
@ -45,18 +56,18 @@ struct Secretive: App {
|
||||
}
|
||||
.commands {
|
||||
CommandGroup(after: CommandGroupPlacement.newItem) {
|
||||
Button("New Secret") {
|
||||
Button("app_menu_new_secret_button") {
|
||||
showingCreation = true
|
||||
}
|
||||
.keyboardShortcut(KeyboardShortcut(KeyEquivalent("N"), modifiers: [.command, .shift]))
|
||||
}
|
||||
CommandGroup(replacing: .help) {
|
||||
Button("Help") {
|
||||
Button("app_menu_help_button") {
|
||||
NSWorkspace.shared.open(Constants.helpURL)
|
||||
}
|
||||
}
|
||||
CommandGroup(after: .help) {
|
||||
Button("Setup Secretive") {
|
||||
Button("app_menu_setup_button") {
|
||||
showingSetup = true
|
||||
}
|
||||
}
|
||||
@ -70,13 +81,12 @@ extension Secretive {
|
||||
|
||||
private func reinstallAgent() {
|
||||
justUpdatedChecker.check()
|
||||
LaunchAgentController().install {
|
||||
// Wait a second for launchd to kick in (next runloop isn't enough).
|
||||
DispatchQueue.main.asyncAfter(deadline: .now() + 1) {
|
||||
agentStatusChecker.check()
|
||||
if !agentStatusChecker.running {
|
||||
forceLaunchAgent()
|
||||
}
|
||||
Task {
|
||||
await LaunchAgentController().install()
|
||||
try? await Task.sleep(for: .seconds(1))
|
||||
agentStatusChecker.check()
|
||||
if !agentStatusChecker.running {
|
||||
forceLaunchAgent()
|
||||
}
|
||||
}
|
||||
}
|
||||
@ -84,7 +94,8 @@ extension Secretive {
|
||||
private func forceLaunchAgent() {
|
||||
// We've run setup, we didn't just update, launchd is just not doing it's thing.
|
||||
// Force a launch directly.
|
||||
LaunchAgentController().forceLaunch { _ in
|
||||
Task {
|
||||
_ = await LaunchAgentController().forceLaunch()
|
||||
agentStatusChecker.check()
|
||||
}
|
||||
}
|
||||
|
@ -2,15 +2,16 @@ import Foundation
|
||||
import Combine
|
||||
import AppKit
|
||||
import SecretKit
|
||||
import Observation
|
||||
|
||||
protocol AgentStatusCheckerProtocol: ObservableObject {
|
||||
protocol AgentStatusCheckerProtocol: Observable {
|
||||
var running: Bool { get }
|
||||
var developmentBuild: Bool { get }
|
||||
}
|
||||
|
||||
class AgentStatusChecker: ObservableObject, AgentStatusCheckerProtocol {
|
||||
@Observable class AgentStatusChecker: AgentStatusCheckerProtocol {
|
||||
|
||||
@Published var running: Bool = false
|
||||
var running: Bool = false
|
||||
|
||||
init() {
|
||||
check()
|
||||
|
@ -6,38 +6,47 @@ import SecretKit
|
||||
|
||||
struct LaunchAgentController {
|
||||
|
||||
func install(completion: (() -> Void)? = nil) {
|
||||
Logger().debug("Installing agent")
|
||||
private let logger = Logger(subsystem: "com.maxgoedjen.secretive", category: "LaunchAgentController")
|
||||
|
||||
func install() async {
|
||||
logger.debug("Installing agent")
|
||||
_ = setEnabled(false)
|
||||
// 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
|
||||
// and start new?
|
||||
DispatchQueue.main.asyncAfter(deadline: .now() + 0.1) {
|
||||
try? await Task.sleep(for: .seconds(1))
|
||||
await MainActor.run {
|
||||
_ = setEnabled(true)
|
||||
completion?()
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
func forceLaunch(completion: ((Bool) -> Void)?) {
|
||||
Logger().debug("Agent is not running, attempting to force launch")
|
||||
func forceLaunch() async -> Bool {
|
||||
logger.debug("Agent is not running, attempting to force launch")
|
||||
let url = Bundle.main.bundleURL.appendingPathComponent("Contents/Library/LoginItems/SecretAgent.app")
|
||||
let config = NSWorkspace.OpenConfiguration()
|
||||
config.activates = false
|
||||
NSWorkspace.shared.openApplication(at: url, configuration: config) { app, error in
|
||||
DispatchQueue.main.async {
|
||||
completion?(error == nil)
|
||||
}
|
||||
if let error = error {
|
||||
Logger().error("Error force launching \(error.localizedDescription)")
|
||||
} else {
|
||||
Logger().debug("Agent force launched")
|
||||
}
|
||||
do {
|
||||
try await NSWorkspace.shared.openApplication(at: url, configuration: config)
|
||||
logger.debug("Agent force launched")
|
||||
return true
|
||||
} catch {
|
||||
logger.error("Error force launching \(error.localizedDescription)")
|
||||
return false
|
||||
}
|
||||
}
|
||||
|
||||
private func setEnabled(_ enabled: Bool) -> Bool {
|
||||
SMLoginItemSetEnabled(Bundle.main.agentBundleID as CFString, enabled)
|
||||
let service = SMAppService.loginItem(identifier: Bundle.main.agentBundleID)
|
||||
do {
|
||||
if enabled {
|
||||
try service.register()
|
||||
} else {
|
||||
try service.unregister()
|
||||
}
|
||||
return true
|
||||
} catch {
|
||||
return false
|
||||
}
|
||||
}
|
||||
|
||||
}
|
||||
|
5235
Sources/Secretive/Localizable.xcstrings
Normal file
5235
Sources/Secretive/Localizable.xcstrings
Normal file
File diff suppressed because it is too large
Load Diff
@ -18,62 +18,69 @@ extension Preview {
|
||||
|
||||
}
|
||||
|
||||
extension Preview {
|
||||
|
||||
class Store: SecretStore, ObservableObject {
|
||||
|
||||
let isAvailable = true
|
||||
let id = UUID()
|
||||
var name: String { "Preview Store" }
|
||||
@Published var secrets: [Secret] = []
|
||||
|
||||
init(secrets: [Secret]) {
|
||||
self.secrets.append(contentsOf: secrets)
|
||||
}
|
||||
|
||||
init(numberOfRandomSecrets: Int = 5) {
|
||||
let new = (0..<numberOfRandomSecrets).map { Secret(name: String(describing: $0)) }
|
||||
self.secrets.append(contentsOf: new)
|
||||
}
|
||||
|
||||
func sign(data: Data, with secret: Preview.Secret, for provenance: SigningRequestProvenance) throws -> Data {
|
||||
return data
|
||||
}
|
||||
|
||||
func existingPersistedAuthenticationContext(secret: Preview.Secret) -> PersistedAuthenticationContext? {
|
||||
nil
|
||||
}
|
||||
|
||||
func persistAuthentication(secret: Preview.Secret, forDuration duration: TimeInterval) throws {
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
class StoreModifiable: Store, SecretStoreModifiable {
|
||||
override var name: String { "Modifiable Preview Store" }
|
||||
|
||||
func create(name: String, requiresAuthentication: Bool) throws {
|
||||
}
|
||||
|
||||
func delete(secret: Preview.Secret) throws {
|
||||
}
|
||||
|
||||
func update(secret: Preview.Secret, name: String) throws {
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
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
|
||||
}
|
||||
|
||||
}
|
||||
//extension Preview {
|
||||
//
|
||||
// class Store: SecretStore, ObservableObject {
|
||||
//
|
||||
// let isAvailable = true
|
||||
// let id = UUID()
|
||||
// var name: String { "Preview Store" }
|
||||
// @Published var secrets: [Secret] = []
|
||||
//
|
||||
// init(secrets: [Secret]) {
|
||||
// self.secrets.append(contentsOf: secrets)
|
||||
// }
|
||||
//
|
||||
// init(numberOfRandomSecrets: Int = 5) {
|
||||
// let new = (0..<numberOfRandomSecrets).map { Secret(name: String(describing: $0)) }
|
||||
// self.secrets.append(contentsOf: new)
|
||||
// }
|
||||
//
|
||||
// func sign(data: Data, with secret: Preview.Secret, for provenance: SigningRequestProvenance) throws -> Data {
|
||||
// return data
|
||||
// }
|
||||
//
|
||||
// func verify(signature data: Data, for signature: Data, with secret: Preview.Secret) throws -> Bool {
|
||||
// true
|
||||
// }
|
||||
//
|
||||
// func existingPersistedAuthenticationContext(secret: Preview.Secret) -> PersistedAuthenticationContext? {
|
||||
// nil
|
||||
// }
|
||||
//
|
||||
// func persistAuthentication(secret: Preview.Secret, forDuration duration: TimeInterval) throws {
|
||||
// }
|
||||
//
|
||||
// func reloadSecrets() {
|
||||
// }
|
||||
//
|
||||
// }
|
||||
//
|
||||
// class StoreModifiable: Store, SecretStoreModifiable {
|
||||
// override var name: String { "Modifiable Preview Store" }
|
||||
//
|
||||
// func create(name: String, requiresAuthentication: Bool) throws {
|
||||
// }
|
||||
//
|
||||
// func delete(secret: Preview.Secret) throws {
|
||||
// }
|
||||
//
|
||||
// func update(secret: Preview.Secret, name: String) throws {
|
||||
// }
|
||||
// }
|
||||
//}
|
||||
//
|
||||
//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
|
||||
// }
|
||||
//
|
||||
//}
|
||||
|
@ -1,20 +1,32 @@
|
||||
import Foundation
|
||||
import Combine
|
||||
import Synchronization
|
||||
import Observation
|
||||
import Brief
|
||||
|
||||
class PreviewUpdater: UpdaterProtocol {
|
||||
@Observable class PreviewUpdater: UpdaterProtocol {
|
||||
|
||||
var update: Release? {
|
||||
_update.withLock { $0 }
|
||||
}
|
||||
let _update: Mutex<Release?> = .init(nil)
|
||||
|
||||
let update: Release?
|
||||
let testBuild = false
|
||||
|
||||
init(update: Update = .none) {
|
||||
switch update {
|
||||
case .none:
|
||||
self.update = nil
|
||||
_update.withLock {
|
||||
$0 = nil
|
||||
}
|
||||
case .advisory:
|
||||
self.update = Release(name: "10.10.10", prerelease: false, html_url: URL(string: "https://example.com")!, body: "Some regular update")
|
||||
_update.withLock {
|
||||
$0 = Release(name: "10.10.10", prerelease: false, html_url: URL(string: "https://example.com")!, body: "Some regular update")
|
||||
}
|
||||
case .critical:
|
||||
self.update = Release(name: "10.10.10", prerelease: false, html_url: URL(string: "https://example.com")!, body: "Critical Security Update")
|
||||
_update.withLock {
|
||||
$0 = Release(name: "10.10.10", prerelease: false, html_url: URL(string: "https://example.com")!, body: "Critical Security Update")
|
||||
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
|
@ -4,15 +4,18 @@ import SecureEnclaveSecretKit
|
||||
import SmartCardSecretKit
|
||||
import Brief
|
||||
|
||||
struct ContentView<UpdaterType: UpdaterProtocol, AgentStatusCheckerType: AgentStatusCheckerProtocol>: View {
|
||||
struct ContentView: View {
|
||||
|
||||
@Binding var showingCreation: Bool
|
||||
@Binding var runningSetup: Bool
|
||||
@Binding var hasRunSetup: Bool
|
||||
@State var showingAgentInfo = false
|
||||
@State var activeSecret: AnySecret.ID?
|
||||
@Environment(\.colorScheme) var colorScheme
|
||||
|
||||
@EnvironmentObject private var storeList: SecretStoreList
|
||||
@EnvironmentObject private var updater: UpdaterType
|
||||
@EnvironmentObject private var agentStatusChecker: AgentStatusCheckerType
|
||||
@Environment(\.secretStoreList) private var storeList: SecretStoreList
|
||||
@Environment(\.updater) private var updater: any UpdaterProtocol
|
||||
@Environment(\.agentStatusChecker) private var agentStatusChecker: any AgentStatusCheckerProtocol
|
||||
|
||||
@State private var selectedUpdate: Release?
|
||||
@State private var showingAppPathNotice = false
|
||||
@ -20,17 +23,17 @@ struct ContentView<UpdaterType: UpdaterProtocol, AgentStatusCheckerType: AgentSt
|
||||
var body: some View {
|
||||
VStack {
|
||||
if storeList.anyAvailable {
|
||||
StoreListView(showingCreation: $showingCreation)
|
||||
StoreListView(activeSecret: $activeSecret)
|
||||
} else {
|
||||
NoStoresView()
|
||||
}
|
||||
}
|
||||
.frame(minWidth: 640, minHeight: 320)
|
||||
.toolbar {
|
||||
updateNotice
|
||||
setupNotice
|
||||
appPathNotice
|
||||
newItem
|
||||
toolbarItem(updateNoticeView, id: "update")
|
||||
toolbarItem(runningOrRunSetupView, id: "setup")
|
||||
toolbarItem(appPathNoticeView, id: "appPath")
|
||||
toolbarItem(newItemView, id: "new")
|
||||
}
|
||||
.sheet(isPresented: $runningSetup) {
|
||||
SetupView(visible: $runningSetup, setupComplete: $hasRunSetup)
|
||||
@ -41,160 +44,190 @@ struct ContentView<UpdaterType: UpdaterProtocol, AgentStatusCheckerType: AgentSt
|
||||
|
||||
extension ContentView {
|
||||
|
||||
var updateNotice: ToolbarItem<Void, AnyView> {
|
||||
guard let update = updater.update else {
|
||||
return ToolbarItem { AnyView(EmptyView()) }
|
||||
|
||||
func toolbarItem(_ view: some View, id: String) -> ToolbarItem<String, some View> {
|
||||
ToolbarItem(id: id) { view }
|
||||
}
|
||||
|
||||
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 {
|
||||
text = "Critical Security Update Required"
|
||||
color = .red
|
||||
return ("update_critical_notice_title", .red)
|
||||
} else {
|
||||
if updater.testBuild {
|
||||
text = "Test Build"
|
||||
color = .blue
|
||||
return ("update_test_notice_title", .blue)
|
||||
} else {
|
||||
text = "Update Available"
|
||||
color = .orange
|
||||
return ("update_normal_notice_title", .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)
|
||||
}
|
||||
)
|
||||
}
|
||||
}
|
||||
|
||||
var newItem: ToolbarItem<Void, AnyView> {
|
||||
guard storeList.modifiableStore?.isAvailable ?? false else {
|
||||
return ToolbarItem { AnyView(EmptyView()) }
|
||||
}
|
||||
return ToolbarItem {
|
||||
AnyView(
|
||||
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")
|
||||
}
|
||||
@ViewBuilder
|
||||
var updateNoticeView: some View {
|
||||
if let update = updater.update, let (text, color) = updateNoticeContent {
|
||||
Button(action: {
|
||||
selectedUpdate = update
|
||||
}, label: {
|
||||
Text(text)
|
||||
.font(.headline)
|
||||
.foregroundColor(.white)
|
||||
})
|
||||
.background(Color.orange)
|
||||
.cornerRadius(5)
|
||||
.popover(isPresented: $showingAppPathNotice, attachmentAnchor: .point(.bottom), arrowEdge: .bottom) {
|
||||
VStack {
|
||||
Image(systemName: "exclamationmark.triangle")
|
||||
.resizable()
|
||||
.aspectRatio(contentMode: .fit)
|
||||
.frame(width: 64)
|
||||
Text("Secretive needs to be in your Applications folder to work properly. Please move it and relaunch.")
|
||||
.frame(maxWidth: 300)
|
||||
}
|
||||
.padding()
|
||||
})
|
||||
.buttonStyle(ToolbarButtonStyle(color: color))
|
||||
.popover(item: $selectedUpdate, attachmentAnchor: attachmentAnchor, arrowEdge: .bottom) { update in
|
||||
UpdateDetailView(update: update)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@ViewBuilder
|
||||
var newItemView: some View {
|
||||
if storeList.modifiableStore?.isAvailable ?? false {
|
||||
Button(action: {
|
||||
showingCreation = true
|
||||
}, 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
|
||||
|
@ -3,11 +3,12 @@ import UniformTypeIdentifiers
|
||||
|
||||
struct CopyableView: View {
|
||||
|
||||
var title: String
|
||||
var title: LocalizedStringKey
|
||||
var image: Image
|
||||
var text: String
|
||||
|
||||
@State private var interactionState: InteractionState = .normal
|
||||
@Environment(\.colorScheme) private var colorScheme
|
||||
|
||||
var body: some View {
|
||||
VStack(alignment: .leading) {
|
||||
@ -65,50 +66,44 @@ struct CopyableView: View {
|
||||
)
|
||||
}
|
||||
|
||||
var hoverText: String {
|
||||
var hoverText: LocalizedStringKey {
|
||||
switch interactionState {
|
||||
case .hovering:
|
||||
return "Click to Copy"
|
||||
return "copyable_click_to_copy_button"
|
||||
case .clicking:
|
||||
return "Copied"
|
||||
return "copyable_copied"
|
||||
case .normal:
|
||||
fatalError()
|
||||
}
|
||||
}
|
||||
|
||||
var backgroundColor: Color {
|
||||
let color: NSColor
|
||||
switch interactionState {
|
||||
case .normal:
|
||||
color = .windowBackgroundColor
|
||||
return colorScheme == .dark ? Color(white: 0.2) : Color(white: 0.885)
|
||||
case .hovering:
|
||||
color = .unemphasizedSelectedContentBackgroundColor
|
||||
return colorScheme == .dark ? Color(white: 0.275) : Color(white: 0.82)
|
||||
case .clicking:
|
||||
color = .selectedContentBackgroundColor
|
||||
return .accentColor
|
||||
}
|
||||
return Color(color)
|
||||
}
|
||||
|
||||
var primaryTextColor: Color {
|
||||
let color: NSColor
|
||||
switch interactionState {
|
||||
case .normal, .hovering:
|
||||
color = .textColor
|
||||
return Color(.textColor)
|
||||
case .clicking:
|
||||
color = .white
|
||||
return .white
|
||||
}
|
||||
return Color(color)
|
||||
}
|
||||
|
||||
var secondaryTextColor: Color {
|
||||
let color: NSColor
|
||||
switch interactionState {
|
||||
case .normal, .hovering:
|
||||
color = .secondaryLabelColor
|
||||
return Color(.secondaryLabelColor)
|
||||
case .clicking:
|
||||
color = .white
|
||||
return .white
|
||||
}
|
||||
return Color(color)
|
||||
}
|
||||
|
||||
func copy() {
|
||||
@ -127,8 +122,10 @@ struct CopyableView: View {
|
||||
struct CopyableView_Previews: PreviewProvider {
|
||||
static var previews: some View {
|
||||
Group {
|
||||
CopyableView(title: "Title", image: Image(systemName: "figure.wave"), text: "Hello world.")
|
||||
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: "Hello world.")
|
||||
.padding()
|
||||
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()
|
||||
}
|
||||
}
|
||||
}
|
||||
|
@ -3,7 +3,7 @@ import SecretKit
|
||||
|
||||
struct CreateSecretView<StoreType: SecretStoreModifiable>: View {
|
||||
|
||||
@ObservedObject var store: StoreType
|
||||
@State var store: StoreType
|
||||
@Binding var showing: Bool
|
||||
|
||||
@State private var name = ""
|
||||
@ -12,38 +12,32 @@ struct CreateSecretView<StoreType: SecretStoreModifiable>: View {
|
||||
var body: some View {
|
||||
VStack {
|
||||
HStack {
|
||||
Image(nsImage: NSApplication.shared.applicationIconImage)
|
||||
.resizable()
|
||||
.frame(width: 64, height: 64)
|
||||
.padding()
|
||||
VStack {
|
||||
HStack {
|
||||
Text("Create a New Secret").bold()
|
||||
Text("create_secret_title")
|
||||
.font(.largeTitle)
|
||||
Spacer()
|
||||
}
|
||||
HStack {
|
||||
Text("Name:")
|
||||
TextField("Shhhhh", text: $name).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()
|
||||
Text("create_secret_name_label")
|
||||
TextField("create_secret_name_placeholder", text: $name)
|
||||
.focusable()
|
||||
}
|
||||
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 {
|
||||
Spacer()
|
||||
Button("Cancel") {
|
||||
Button("create_secret_cancel_button") {
|
||||
showing = false
|
||||
}
|
||||
.keyboardShortcut(.cancelAction)
|
||||
Button("Create", action: save)
|
||||
Button("create_secret_create_button", action: save)
|
||||
.disabled(name.isEmpty)
|
||||
.keyboardShortcut(.defaultAction)
|
||||
}
|
||||
@ -51,7 +45,206 @@ struct CreateSecretView<StoreType: SecretStoreModifiable>: View {
|
||||
}
|
||||
|
||||
func save() {
|
||||
try! store.create(name: name, requiresAuthentication: requiresAuthentication)
|
||||
showing = false
|
||||
Task {
|
||||
try! await store.create(name: name, requiresAuthentication: requiresAuthentication)
|
||||
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
|
||||
|
@ -3,7 +3,7 @@ import SecretKit
|
||||
|
||||
struct DeleteSecretView<StoreType: SecretStoreModifiable>: View {
|
||||
|
||||
@ObservedObject var store: StoreType
|
||||
@State var store: StoreType
|
||||
let secret: StoreType.SecretType
|
||||
var dismissalBlock: (Bool) -> ()
|
||||
|
||||
@ -18,25 +18,24 @@ struct DeleteSecretView<StoreType: SecretStoreModifiable>: View {
|
||||
.padding()
|
||||
VStack {
|
||||
HStack {
|
||||
Text("Delete \(secret.name)?").bold()
|
||||
Text("delete_confirmation_title_\(secret.name)").bold()
|
||||
Spacer()
|
||||
}
|
||||
HStack {
|
||||
Text("If you delete \(secret.name), you will not be able to recover it. Type \"\(secret.name)\" to confirm.")
|
||||
Text("delete_confirmation_description_\(secret.name)_\(secret.name)")
|
||||
Spacer()
|
||||
}
|
||||
HStack {
|
||||
Text("Confirm Name:")
|
||||
Text("delete_confirmation_confirm_name_label")
|
||||
TextField(secret.name, text: $confirm)
|
||||
}
|
||||
}
|
||||
}
|
||||
HStack {
|
||||
Spacer()
|
||||
Button("Delete", action: delete)
|
||||
Button("delete_confirmation_delete_button", action: delete)
|
||||
.disabled(confirm != secret.name)
|
||||
.keyboardShortcut(.delete)
|
||||
Button("Don't Delete") {
|
||||
Button("delete_confirmation_cancel_button") {
|
||||
dismissalBlock(false)
|
||||
}
|
||||
.keyboardShortcut(.cancelAction)
|
||||
@ -50,8 +49,10 @@ struct DeleteSecretView<StoreType: SecretStoreModifiable>: View {
|
||||
}
|
||||
|
||||
func delete() {
|
||||
try! store.delete(secret: secret)
|
||||
dismissalBlock(true)
|
||||
Task {
|
||||
try! await store.delete(secret: secret)
|
||||
dismissalBlock(true)
|
||||
}
|
||||
}
|
||||
|
||||
}
|
||||
|
@ -3,17 +3,17 @@ import SecretKit
|
||||
|
||||
struct EmptyStoreView: View {
|
||||
|
||||
@ObservedObject var store: AnySecretStore
|
||||
@State var store: AnySecretStore
|
||||
@Binding var activeSecret: AnySecret.ID?
|
||||
|
||||
var body: some View {
|
||||
if store is AnySecretStoreModifiable {
|
||||
NavigationLink(destination: EmptyStoreModifiableView(), tag: Constants.emptyStoreModifiableTag, selection: $activeSecret) {
|
||||
Text("No Secrets")
|
||||
Text("empty_store_modifiable_title")
|
||||
}
|
||||
} else {
|
||||
NavigationLink(destination: EmptyStoreImmutableView(), tag: Constants.emptyStoreTag, selection: $activeSecret) {
|
||||
Text("No Secrets")
|
||||
Text("empty_store_nonmodifiable_title")
|
||||
}
|
||||
}
|
||||
}
|
||||
@ -22,8 +22,8 @@ struct EmptyStoreView: View {
|
||||
extension EmptyStoreView {
|
||||
|
||||
enum Constants {
|
||||
static let emptyStoreModifiableTag: AnyHashable = "emptyStoreModifiableTag"
|
||||
static let emptyStoreTag: AnyHashable = "emptyStoreModifiableTag"
|
||||
static let emptyStoreModifiableTag = "emptyStoreModifiableTag"
|
||||
static let emptyStoreTag = "emptyStoreTag"
|
||||
}
|
||||
|
||||
}
|
||||
@ -32,9 +32,9 @@ struct EmptyStoreImmutableView: View {
|
||||
|
||||
var body: some View {
|
||||
VStack {
|
||||
Text("No Secrets").bold()
|
||||
Text("Use your Smart Card's management tool to create a secret.")
|
||||
Text("Secretive only supports Elliptic Curve keys.")
|
||||
Text("empty_store_nonmodifiable_title").bold()
|
||||
Text("empty_store_nonmodifiable_description")
|
||||
Text("empty_store_nonmodifiable_supported_key_types")
|
||||
}.frame(maxWidth: .infinity, maxHeight: .infinity)
|
||||
}
|
||||
|
||||
@ -63,8 +63,8 @@ struct EmptyStoreModifiableView: View {
|
||||
path.addLine(to: CGPoint(x: g.size.width - 3, y: 0))
|
||||
}.fill()
|
||||
}.frame(height: (windowGeometry.size.height/2) - 20).padding()
|
||||
Text("No Secrets").bold()
|
||||
Text("Create a new one by clicking here.")
|
||||
Text("empty_store_modifiable_click_here_title").bold()
|
||||
Text("empty_store_modifiable_click_here_description")
|
||||
Spacer()
|
||||
}.frame(maxWidth: .infinity, maxHeight: .infinity)
|
||||
}
|
||||
|
@ -4,9 +4,10 @@ struct NoStoresView: View {
|
||||
|
||||
var body: some View {
|
||||
VStack {
|
||||
Text("No Secure Storage Available").bold()
|
||||
Text("Your Mac doesn't have a Secure Enclave, and there's not a compatible Smart Card inserted.")
|
||||
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/")!)
|
||||
Text("no_secure_storage_title")
|
||||
.bold()
|
||||
Text("no_secure_storage_description")
|
||||
Link("no_secure_storage_yubico_link", destination: URL(string: "https://www.yubico.com/products/compare-yubikey-5-series/")!)
|
||||
}.padding()
|
||||
}
|
||||
|
||||
|
@ -3,7 +3,7 @@ import SecretKit
|
||||
|
||||
struct RenameSecretView<StoreType: SecretStoreModifiable>: View {
|
||||
|
||||
@ObservedObject var store: StoreType
|
||||
@State var store: StoreType
|
||||
let secret: StoreType.SecretType
|
||||
var dismissalBlock: (_ renamed: Bool) -> ()
|
||||
|
||||
@ -18,7 +18,7 @@ struct RenameSecretView<StoreType: SecretStoreModifiable>: View {
|
||||
.padding()
|
||||
VStack {
|
||||
HStack {
|
||||
Text("Type your new name for \"\(secret.name)\" below.")
|
||||
Text("rename_title_\(secret.name)")
|
||||
Spacer()
|
||||
}
|
||||
HStack {
|
||||
@ -28,10 +28,10 @@ struct RenameSecretView<StoreType: SecretStoreModifiable>: View {
|
||||
}
|
||||
HStack {
|
||||
Spacer()
|
||||
Button("Rename", action: rename)
|
||||
Button("rename_rename_button", action: rename)
|
||||
.disabled(newName.count == 0)
|
||||
.keyboardShortcut(.return)
|
||||
Button("Cancel") {
|
||||
Button("rename_cancel_button") {
|
||||
dismissalBlock(false)
|
||||
}.keyboardShortcut(.cancelAction)
|
||||
}
|
||||
@ -44,7 +44,9 @@ struct RenameSecretView<StoreType: SecretStoreModifiable>: View {
|
||||
}
|
||||
|
||||
func rename() {
|
||||
try? store.update(secret: secret, name: newName)
|
||||
dismissalBlock(true)
|
||||
Task {
|
||||
try? await store.update(secret: secret, name: newName)
|
||||
dismissalBlock(true)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
@ -12,16 +12,16 @@ struct SecretDetailView<SecretType: Secret>: View {
|
||||
ScrollView {
|
||||
Form {
|
||||
Section {
|
||||
CopyableView(title: "SHA256 Fingerprint", image: Image(systemName: "touchid"), text: keyWriter.openSSHSHA256Fingerprint(secret: secret))
|
||||
CopyableView(title: "secret_detail_sha256_fingerprint_label", image: Image(systemName: "touchid"), text: keyWriter.openSSHSHA256Fingerprint(secret: secret))
|
||||
Spacer()
|
||||
.frame(height: 20)
|
||||
CopyableView(title: "MD5 Fingerprint", image: Image(systemName: "touchid"), text: keyWriter.openSSHMD5Fingerprint(secret: secret))
|
||||
CopyableView(title: "secret_detail_md5_fingerprint_label", image: Image(systemName: "touchid"), text: keyWriter.openSSHMD5Fingerprint(secret: secret))
|
||||
Spacer()
|
||||
.frame(height: 20)
|
||||
CopyableView(title: "Public Key", image: Image(systemName: "key"), text: keyString)
|
||||
CopyableView(title: "secret_detail_public_key_label", image: Image(systemName: "key"), text: keyString)
|
||||
Spacer()
|
||||
.frame(height: 20)
|
||||
CopyableView(title: "Public Key Path", image: Image(systemName: "lock.doc"), text: publicKeyFileStoreController.path(for: secret))
|
||||
CopyableView(title: "secret_detail_public_key_path_label", image: Image(systemName: "lock.doc"), text: publicKeyFileStoreController.publicKeyPath(for: secret))
|
||||
Spacer()
|
||||
}
|
||||
}
|
||||
@ -47,12 +47,12 @@ struct SecretDetailView<SecretType: Secret>: View {
|
||||
|
||||
}
|
||||
|
||||
#if DEBUG
|
||||
|
||||
struct SecretDetailView_Previews: PreviewProvider {
|
||||
static var previews: some View {
|
||||
SecretDetailView(secret: Preview.Store(numberOfRandomSecrets: 1).secrets[0])
|
||||
}
|
||||
}
|
||||
|
||||
#endif
|
||||
//#if DEBUG
|
||||
//
|
||||
//struct SecretDetailView_Previews: PreviewProvider {
|
||||
// static var previews: some View {
|
||||
// SecretDetailView(secret: Preview.Store(numberOfRandomSecrets: 1).secrets[0])
|
||||
// }
|
||||
//}
|
||||
//
|
||||
//#endif
|
||||
|
@ -3,7 +3,7 @@ import SecretKit
|
||||
|
||||
struct SecretListItemView: View {
|
||||
|
||||
@ObservedObject var store: AnySecretStore
|
||||
@State var store: AnySecretStore
|
||||
var secret: AnySecret
|
||||
@Binding var activeSecret: AnySecret.ID?
|
||||
|
||||
@ -29,13 +29,14 @@ struct SecretListItemView: View {
|
||||
} else {
|
||||
Text(secret.name)
|
||||
}
|
||||
}.contextMenu {
|
||||
}
|
||||
.contextMenu {
|
||||
if store is AnySecretStoreModifiable {
|
||||
Button(action: { isRenaming = true }) {
|
||||
Text("Rename")
|
||||
Text("secret_list_rename_button")
|
||||
}
|
||||
Button(action: { isDeleting = true }) {
|
||||
Text("Delete")
|
||||
Text("secret_list_delete_button")
|
||||
}
|
||||
}
|
||||
}
|
||||
|
@ -26,7 +26,7 @@ struct SetupView: View {
|
||||
}
|
||||
}
|
||||
}
|
||||
.frame(idealWidth: 500, idealHeight: 500)
|
||||
.frame(minWidth: 500, idealWidth: 500, minHeight: 500, idealHeight: 500)
|
||||
}
|
||||
|
||||
|
||||
@ -61,7 +61,7 @@ struct StepView: View {
|
||||
Circle()
|
||||
.foregroundColor(.green)
|
||||
.frame(width: Constants.circleWidth, height: Constants.circleWidth)
|
||||
Text("✓")
|
||||
Text("setup_step_complete_symbol")
|
||||
.foregroundColor(.white)
|
||||
.bold()
|
||||
} else {
|
||||
@ -101,14 +101,14 @@ extension StepView {
|
||||
|
||||
struct SetupStepView<Content> : View where Content : View {
|
||||
|
||||
let title: String
|
||||
let title: LocalizedStringKey
|
||||
let image: Image
|
||||
let bodyText: String
|
||||
let buttonTitle: String
|
||||
let bodyText: LocalizedStringKey
|
||||
let buttonTitle: LocalizedStringKey
|
||||
let buttonAction: () -> Void
|
||||
let content: Content
|
||||
|
||||
init(title: String, image: Image, bodyText: String, buttonTitle: String, buttonAction: @escaping () -> Void = {}, @ViewBuilder content: () -> Content) {
|
||||
init(title: LocalizedStringKey, image: Image, bodyText: LocalizedStringKey, buttonTitle: LocalizedStringKey, buttonAction: @escaping () -> Void = {}, @ViewBuilder content: () -> Content) {
|
||||
self.title = title
|
||||
self.image = image
|
||||
self.bodyText = bodyText
|
||||
@ -145,19 +145,21 @@ struct SecretAgentSetupView: View {
|
||||
let buttonAction: () -> Void
|
||||
|
||||
var body: some View {
|
||||
SetupStepView(title: "Setup Secret Agent",
|
||||
SetupStepView(title: "setup_agent_title",
|
||||
image: Image(nsImage: NSApplication.shared.applicationIconImage),
|
||||
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: "Install",
|
||||
bodyText: "setup_agent_description",
|
||||
buttonTitle: "setup_agent_install_button",
|
||||
buttonAction: install) {
|
||||
(Text("This helper app is called ") + Text("Secret Agent").bold().underline() + Text(" and you may see it in Activity Manager from time to time."))
|
||||
Text("setup_agent_activity_monitor_description")
|
||||
.multilineTextAlignment(.center)
|
||||
}
|
||||
}
|
||||
|
||||
func install() {
|
||||
LaunchAgentController().install()
|
||||
buttonAction()
|
||||
Task {
|
||||
await LaunchAgentController().install()
|
||||
buttonAction()
|
||||
}
|
||||
}
|
||||
|
||||
}
|
||||
@ -170,12 +172,12 @@ struct SSHAgentSetupView: View {
|
||||
@State private var selectedShellInstruction: ShellConfigInstruction = controller.shellInstructions.first!
|
||||
|
||||
var body: some View {
|
||||
SetupStepView(title: "Configure your SSH Agent",
|
||||
SetupStepView(title: "setup_ssh_title",
|
||||
image: Image(systemName: "terminal"),
|
||||
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: "I Added it Manually",
|
||||
bodyText: "setup_ssh_description",
|
||||
buttonTitle: "setup_ssh_added_manually_button",
|
||||
buttonAction: buttonAction) {
|
||||
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")!)
|
||||
Link("setup_third_party_faq_link", destination: URL(string: "https://github.com/maxgoedjen/secretive/blob/main/APP_CONFIG.md")!)
|
||||
Picker(selection: $selectedShellInstruction, label: EmptyView()) {
|
||||
ForEach(SSHAgentSetupView.controller.shellInstructions) { instruction in
|
||||
Text(instruction.shell)
|
||||
@ -183,8 +185,8 @@ struct SSHAgentSetupView: View {
|
||||
.padding()
|
||||
}
|
||||
}.pickerStyle(SegmentedPickerStyle())
|
||||
CopyableView(title: "Add to \(selectedShellInstruction.shellConfigPath)", image: Image(systemName: "greaterthan.square"), text: selectedShellInstruction.text)
|
||||
Button("Add it For Me") {
|
||||
CopyableView(title: "setup_ssh_add_to_config_button_\(selectedShellInstruction.shellConfigPath)", image: Image(systemName: "greaterthan.square"), text: selectedShellInstruction.text)
|
||||
Button("setup_ssh_add_for_me_button") {
|
||||
let controller = ShellConfigurationController()
|
||||
if controller.addToShell(shellInstructions: selectedShellInstruction) {
|
||||
buttonAction()
|
||||
@ -214,12 +216,12 @@ struct UpdaterExplainerView: View {
|
||||
let buttonAction: () -> Void
|
||||
|
||||
var body: some View {
|
||||
SetupStepView(title: "Updates",
|
||||
SetupStepView(title: "setup_updates_title",
|
||||
image: Image(systemName: "dot.radiowaves.left.and.right"),
|
||||
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: "Okay",
|
||||
bodyText: "setup_updates_description",
|
||||
buttonTitle: "setup_updates_ok",
|
||||
buttonAction: buttonAction) {
|
||||
Link("Read more about this here.", destination: SetupView.Constants.updaterFAQURL)
|
||||
Link("setup_updates_readmore", destination: SetupView.Constants.updaterFAQURL)
|
||||
}
|
||||
}
|
||||
|
||||
|
@ -1,20 +1,19 @@
|
||||
import SwiftUI
|
||||
import Combine
|
||||
import SecretKit
|
||||
|
||||
struct StoreListView: View {
|
||||
|
||||
@Binding var showingCreation: Bool
|
||||
@Binding var activeSecret: AnySecret.ID?
|
||||
|
||||
@State private var activeSecret: AnySecret.ID?
|
||||
|
||||
@EnvironmentObject private var storeList: SecretStoreList
|
||||
@Environment(SecretStoreList.self) private var storeList: SecretStoreList
|
||||
|
||||
private func secretDeleted(secret: AnySecret) {
|
||||
activeSecret = nextDefaultSecret
|
||||
}
|
||||
|
||||
private func secretRenamed(secret: AnySecret) {
|
||||
activeSecret = nextDefaultSecret
|
||||
activeSecret = secret.id
|
||||
}
|
||||
|
||||
var body: some View {
|
||||
|
37
Sources/Secretive/Views/ToolbarButtonStyle.swift
Normal file
37
Sources/Secretive/Views/ToolbarButtonStyle.swift
Normal file
@ -0,0 +1,37 @@
|
||||
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
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
@ -3,26 +3,28 @@ import Brief
|
||||
|
||||
struct UpdateDetailView<UpdaterType: Updater>: View {
|
||||
|
||||
@EnvironmentObject var updater: UpdaterType
|
||||
@Environment(UpdaterType.self) var updater: UpdaterType
|
||||
|
||||
let update: Release
|
||||
|
||||
var body: some View {
|
||||
VStack {
|
||||
Text("Secretive \(update.name)").font(.title)
|
||||
GroupBox(label: Text("Release Notes")) {
|
||||
Text("update_version_name_\(update.name)").font(.title)
|
||||
GroupBox(label: Text("update_release_notes_title")) {
|
||||
ScrollView {
|
||||
attributedBody
|
||||
}
|
||||
}
|
||||
HStack {
|
||||
if !update.critical {
|
||||
Button("Ignore") {
|
||||
updater.ignore(release: update)
|
||||
Button("update_ignore_button") {
|
||||
Task {
|
||||
await updater.ignore(release: update)
|
||||
}
|
||||
}
|
||||
Spacer()
|
||||
}
|
||||
Button("Update") {
|
||||
Button("update_update_button") {
|
||||
NSWorkspace.shared.open(update.html_url)
|
||||
}
|
||||
.keyboardShortcut(.defaultAction)
|
||||
@ -34,24 +36,24 @@ struct UpdateDetailView<UpdaterType: Updater>: View {
|
||||
}
|
||||
|
||||
var attributedBody: Text {
|
||||
var text = Text("")
|
||||
var text = Text(verbatim: "")
|
||||
for line in update.body.split(whereSeparator: \.isNewline) {
|
||||
let attributed: Text
|
||||
let split = line.split(separator: " ")
|
||||
let unprefixed = split.dropFirst().joined()
|
||||
let unprefixed = split.dropFirst().joined(separator: " ")
|
||||
if let prefix = split.first {
|
||||
switch prefix {
|
||||
case "#":
|
||||
attributed = Text(unprefixed).font(.title) + Text("\n")
|
||||
attributed = Text(unprefixed).font(.title) + Text(verbatim: "\n")
|
||||
case "##":
|
||||
attributed = Text(unprefixed).font(.title2) + Text("\n")
|
||||
attributed = Text(unprefixed).font(.title2) + Text(verbatim: "\n")
|
||||
case "###":
|
||||
attributed = Text(unprefixed).font(.title3) + Text("\n")
|
||||
attributed = Text(unprefixed).font(.title3) + Text(verbatim: "\n")
|
||||
default:
|
||||
attributed = Text(line) + Text("\n\n")
|
||||
attributed = Text(line) + Text(verbatim: "\n\n")
|
||||
}
|
||||
} else {
|
||||
attributed = Text(line) + Text("\n\n")
|
||||
attributed = Text(line) + Text(verbatim: "\n\n")
|
||||
}
|
||||
text = text + attributed
|
||||
}
|
||||
|
@ -1,22 +0,0 @@
|
||||
<?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>
|
@ -1,20 +0,0 @@
|
||||
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.
|
||||
}
|
||||
|
||||
|
||||
}
|
Reference in New Issue
Block a user