mirror of
https://github.com/maxgoedjen/secretive.git
synced 2025-07-01 01:33:37 +00:00
Compare commits
32 Commits
async
...
restartage
Author | SHA1 | Date | |
---|---|---|---|
9fc7d2548e | |||
8679ca3da0 | |||
f43571baa3 | |||
acdf0baf3a | |||
1a362ef955 | |||
3b254d33a5 | |||
382913cb99 | |||
20cbaac6f6 | |||
47d736cb0d | |||
fa0e81cd8e | |||
e31db0f4fa | |||
403709ac83 | |||
5f055efa18 | |||
e77812c06c | |||
8744313ba1 | |||
26d6ced9ee | |||
71b4780488 | |||
84dd9403c3 | |||
0af7b803bc | |||
a1009d0dac | |||
ae7394f771 | |||
6ea0a3ebd2 | |||
067f1526b0 | |||
f43dea0d0d | |||
db8833fa25 | |||
1409e9ac31 | |||
adabe801d3 | |||
19f9494492 | |||
c50d2feaf9 | |||
03d3cc9177 | |||
141cc03b60 | |||
07559bd7ef |
BIN
.github/readme/app.png
vendored
BIN
.github/readme/app.png
vendored
Binary file not shown.
Before Width: | Height: | Size: 456 KiB After Width: | Height: | Size: 580 KiB |
BIN
.github/readme/notification.png
vendored
BIN
.github/readme/notification.png
vendored
Binary file not shown.
Before Width: | Height: | Size: 1.1 MiB After Width: | Height: | Size: 1.0 MiB |
BIN
.github/readme/touchid.png
vendored
BIN
.github/readme/touchid.png
vendored
Binary file not shown.
Before Width: | Height: | Size: 190 KiB After Width: | Height: | Size: 259 KiB |
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@v0.0.3
|
||||
with:
|
||||
project-url: https://github.com/users/maxgoedjen/projects/1
|
||||
github-token: ${{ secrets.ADD_TO_PROJECT_PAT }}
|
53
.github/workflows/nightly.yml
vendored
Normal file
53
.github/workflows/nightly.yml
vendored
Normal file
@ -0,0 +1,53 @@
|
||||
name: Nightly
|
||||
|
||||
on:
|
||||
schedule:
|
||||
- cron: "0 8 * * *"
|
||||
jobs:
|
||||
build:
|
||||
runs-on: macOS-latest
|
||||
timeout-minutes: 10
|
||||
steps:
|
||||
- uses: actions/checkout@v2
|
||||
- name: Setup Signing
|
||||
env:
|
||||
SIGNING_DATA: ${{ secrets.SIGNING_DATA }}
|
||||
SIGNING_PASSWORD: ${{ secrets.SIGNING_PASSWORD }}
|
||||
HOST_PROFILE_DATA: ${{ secrets.HOST_PROFILE_DATA }}
|
||||
AGENT_PROFILE_DATA: ${{ secrets.AGENT_PROFILE_DATA }}
|
||||
APPLE_API_KEY_DATA: ${{ secrets.APPLE_API_KEY_DATA }}
|
||||
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_14.1.app
|
||||
- name: Update Build Number
|
||||
env:
|
||||
RUN_ID: ${{ github.run_id }}
|
||||
run: |
|
||||
sed -i '' -e "s/GITHUB_CI_VERSION/0.0.0/g" Sources/Config/Config.xcconfig
|
||||
sed -i '' -e "s/GITHUB_BUILD_NUMBER/1.$RUN_ID/g" Sources/Config/Config.xcconfig
|
||||
sed -i '' -e "s/GITHUB_BUILD_URL/https:\/\/github.com\/maxgoedjen\/secretive\/actions\/runs\/$RUN_ID/g" Sources/Secretive/Credits.rtf
|
||||
- name: Build
|
||||
run: xcrun xcodebuild -project Sources/Secretive.xcodeproj -scheme Secretive -configuration Release -archivePath Archive.xcarchive archive
|
||||
- name: Create ZIPs
|
||||
run: |
|
||||
ditto -c -k --sequesterRsrc --keepParent Archive.xcarchive/Products/Applications/Secretive.app ./Secretive.zip
|
||||
ditto -c -k --sequesterRsrc --keepParent Archive.xcarchive ./Archive.zip
|
||||
- name: Notarize
|
||||
env:
|
||||
APPLE_API_KEY_ID: ${{ secrets.APPLE_API_KEY_ID }}
|
||||
APPLE_API_ISSUER: ${{ secrets.APPLE_API_ISSUER }}
|
||||
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
|
||||
with:
|
||||
name: Secretive.zip
|
||||
path: Secretive.zip
|
12
.github/workflows/release.yml
vendored
12
.github/workflows/release.yml
vendored
@ -6,7 +6,7 @@ on:
|
||||
- '*'
|
||||
jobs:
|
||||
test:
|
||||
runs-on: macos-11.0
|
||||
runs-on: macOS-latest
|
||||
timeout-minutes: 10
|
||||
steps:
|
||||
- uses: actions/checkout@v1
|
||||
@ -20,14 +20,14 @@ 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_14.1.app
|
||||
- name: Test
|
||||
run: |
|
||||
pushd Sources/Packages
|
||||
swift test
|
||||
popd
|
||||
build:
|
||||
runs-on: macos-11.0
|
||||
runs-on: macOS-latest
|
||||
timeout-minutes: 10
|
||||
steps:
|
||||
- uses: actions/checkout@v2
|
||||
@ -41,7 +41,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_14.1.app
|
||||
- name: Update Build Number
|
||||
env:
|
||||
TAG_NAME: ${{ github.ref }}
|
||||
@ -64,8 +64,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
|
||||
|
4
.github/workflows/test.yml
vendored
4
.github/workflows/test.yml
vendored
@ -3,12 +3,12 @@ name: Test
|
||||
on: [push, pull_request]
|
||||
jobs:
|
||||
test:
|
||||
runs-on: macos-11.0
|
||||
runs-on: macOS-latest
|
||||
timeout-minutes: 10
|
||||
steps:
|
||||
- uses: actions/checkout@v2
|
||||
- name: Set Environment
|
||||
run: sudo xcrun xcode-select -s /Applications/Xcode_13.2.1.app
|
||||
run: sudo xcrun xcode-select -s /Applications/Xcode_14.1.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,55 @@ 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`
|
||||
|
||||
```
|
||||
<?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 Gitkraken. Then enable "Use local SSH agent in GitKraken Preferences (Located under Preferences -> SSH)
|
||||
|
||||
# The app I use isn't listed here!
|
||||
|
||||
|
14
FAQ.md
14
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:
|
||||
@ -26,7 +30,11 @@ Please run `ssh -Tv git@github.com` in your terminal and paste the output in a [
|
||||
|
||||
### How do I tell SSH to use a specific key?
|
||||
|
||||
You can create a `mykey.pub` (where `mykey` is the name of your key) in your `~/.ssh/` directory with the contents of your public key, and specify that you want to use that key in your `~/.ssh/config`. [This ServerFault answer](https://serverfault.com/a/295771) has more details on setting that up
|
||||
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.
|
||||
|
||||
### Can I use Secretive for SSH Agent Forwarding?
|
||||
|
||||
Yes, you can! Once you've set up Secretive, just add `ForwardAgent yes` to the hosts you want to forward to in your SSH config file. Afterwards, any use of one of your SSH keys on the remote host must be authenticated through Secretive.
|
||||
|
||||
### Why should I trust you?
|
||||
|
||||
@ -40,6 +48,10 @@ Awesome! Just bear in mind that because an app only has access to the keychain i
|
||||
|
||||
Secretive checks in with GitHub's releases API to check if there's a new version of Secretive available. You can audit the source code for this feature [here](https://github.com/maxgoedjen/secretive/blob/main/Sources/Packages/Sources/Brief/Updater.swift).
|
||||
|
||||
### How do I uninstall Secretive?
|
||||
|
||||
Drag Secretive.app to the trash and remove `~/Library/Containers/com.maxgoedjen.Secretive.SecretAgent`. `SecretAgent` may continue running until you quit it or reboot.
|
||||
|
||||
### I have a security issue
|
||||
|
||||
Please contact [max.goedjen@gmail.com](mailto:max.goedjen@gmail.com) with a subject containing "SECRETIVE SECURITY" immediately with details, and I'll address the issue and credit you ASAP.
|
||||
|
@ -16,13 +16,13 @@ The most common setup for SSH keys is just keeping them on disk, guarded by prop
|
||||
|
||||
If your Mac has a Secure Enclave, it also has support for strong access controls like Touch ID, or authentication with Apple Watch. You can configure your key so that they require Touch ID (or Watch) authentication before they're accessed.
|
||||
|
||||
<img src="/.github/readme/touchid.png" alt="Screenshot of Secretive authenticating with Touch ID">
|
||||
<img src="/.github/readme/touchid.png" alt="Screenshot of Secretive authenticating with Touch ID" width="400">
|
||||
|
||||
### Notifications
|
||||
|
||||
Secretive also notifies you whenever your keys are accessed, so you're never caught off guard.
|
||||
|
||||
<img src="/.github/readme/notification.png" alt="Screenshot of Secretive notifying the user">
|
||||
<img src="/.github/readme/notification.png" alt="Screenshot of Secretive notifying the user" width="600">
|
||||
|
||||
### Support for Smart Cards Too!
|
||||
|
||||
|
@ -1,7 +1,7 @@
|
||||
import Foundation
|
||||
|
||||
/// A release is a representation of a downloadable update.
|
||||
public struct Release: Codable, Sendable {
|
||||
public struct Release: Codable {
|
||||
|
||||
/// The user-facing name of the release. Typically "Secretive 1.2.3"
|
||||
public let name: String
|
||||
@ -30,9 +30,6 @@ public struct Release: Codable, Sendable {
|
||||
|
||||
}
|
||||
|
||||
// TODO: REMOVE WHEN(?) URL GAINS NATIVE CONFORMANCE
|
||||
extension URL: @unchecked Sendable {}
|
||||
|
||||
extension Release: Identifiable {
|
||||
|
||||
public var id: String {
|
||||
|
@ -1,7 +1,7 @@
|
||||
import Foundation
|
||||
|
||||
/// A representation of a Semantic Version.
|
||||
public struct SemVer: Sendable {
|
||||
public struct SemVer {
|
||||
|
||||
/// The SemVer broken into an array of integers.
|
||||
let versionNumbers: [Int]
|
||||
|
@ -2,59 +2,53 @@ import Foundation
|
||||
import Combine
|
||||
|
||||
/// A concrete implementation of ``UpdaterProtocol`` which considers the current release and OS version.
|
||||
public actor Updater: ObservableObject, UpdaterProtocol {
|
||||
public class Updater: ObservableObject, UpdaterProtocol {
|
||||
|
||||
@MainActor @Published public var update: Release?
|
||||
@Published public var update: Release?
|
||||
public let testBuild: Bool
|
||||
|
||||
/// The current OS version.
|
||||
private let osVersion: SemVer
|
||||
/// The current version of the app that is running.
|
||||
private let currentVersion: SemVer
|
||||
/// The timer responsible for checking for updates regularly.
|
||||
private var timer: Timer? = nil
|
||||
|
||||
/// Initializes an Updater.
|
||||
/// - Parameters:
|
||||
/// - checkOnLaunch: A boolean describing whether the Updater should check for available updates on launch.
|
||||
/// - checkFrequency: The interval at which the Updater should check for updates. Subject to a tolerance of 1 hour.
|
||||
/// - osVersion: The current OS version.
|
||||
/// - currentVersion: The current version of the app that is running.
|
||||
public init(osVersion: SemVer = SemVer(ProcessInfo.processInfo.operatingSystemVersion), currentVersion: SemVer = SemVer(Bundle.main.infoDictionary?["CFBundleShortVersionString"] as? String ?? "0.0.0")) {
|
||||
public init(checkOnLaunch: Bool, checkFrequency: TimeInterval = Measurement(value: 24, unit: UnitDuration.hours).converted(to: .seconds).value, osVersion: SemVer = SemVer(ProcessInfo.processInfo.operatingSystemVersion), currentVersion: SemVer = SemVer(Bundle.main.infoDictionary?["CFBundleShortVersionString"] as? String ?? "0.0.0")) {
|
||||
self.osVersion = osVersion
|
||||
self.currentVersion = currentVersion
|
||||
testBuild = currentVersion == SemVer("0.0.0")
|
||||
}
|
||||
|
||||
/// Begins checking for updates with the specified frequency.
|
||||
/// - Parameter checkFrequency: The interval at which the Updater should check for updates. Subject to a tolerance of 1 hour.
|
||||
public func beginChecking(checkFrequency: TimeInterval = Measurement(value: 24, unit: UnitDuration.hours).converted(to: .seconds).value) {
|
||||
timer?.invalidate()
|
||||
timer = Timer.scheduledTimer(withTimeInterval: checkFrequency, repeats: true) { _ in
|
||||
Task {
|
||||
await self.checkForUpdates()
|
||||
}
|
||||
if checkOnLaunch {
|
||||
// Don't do a launch check if the user hasn't seen the setup prompt explaining updater yet.
|
||||
checkForUpdates()
|
||||
}
|
||||
timer?.tolerance = 60*60
|
||||
}
|
||||
|
||||
/// Ends checking for updates.
|
||||
public func stopChecking() {
|
||||
timer?.invalidate()
|
||||
timer = nil
|
||||
let timer = Timer.scheduledTimer(withTimeInterval: checkFrequency, repeats: true) { _ in
|
||||
self.checkForUpdates()
|
||||
}
|
||||
timer.tolerance = 60*60
|
||||
}
|
||||
|
||||
/// Manually trigger an update check.
|
||||
public func checkForUpdates() async {
|
||||
guard let (data, _) = try? await URLSession.shared.data(from: Constants.updateURL),
|
||||
let releases = try? JSONDecoder().decode([Release].self, from: data) else { return }
|
||||
await evaluate(releases: releases)
|
||||
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()
|
||||
}
|
||||
|
||||
/// 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) async {
|
||||
public func ignore(release: Release) {
|
||||
guard !release.critical else { return }
|
||||
defaults.set(true, forKey: release.name)
|
||||
await setUpdate(update: update)
|
||||
DispatchQueue.main.async {
|
||||
self.update = nil
|
||||
}
|
||||
}
|
||||
|
||||
}
|
||||
@ -63,7 +57,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]) async {
|
||||
func evaluate(releases: [Release]) {
|
||||
guard let release = releases
|
||||
.sorted()
|
||||
.reversed()
|
||||
@ -73,14 +67,12 @@ extension Updater {
|
||||
guard !release.prerelease else { return }
|
||||
let latestVersion = SemVer(release.name)
|
||||
if latestVersion > currentVersion {
|
||||
await setUpdate(update: update)
|
||||
DispatchQueue.main.async {
|
||||
self.update = release
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@MainActor private func setUpdate(update: Release?) {
|
||||
self.update = update
|
||||
}
|
||||
|
||||
/// Checks whether the user has ignored a release.
|
||||
/// - Parameter release: The release to check.
|
||||
/// - Returns: A boolean describing whether the user has ignored the release. Will always be false if the release is critical.
|
||||
@ -103,21 +95,3 @@ extension Updater {
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
@available(macOS, deprecated: 12)
|
||||
extension URLSession {
|
||||
|
||||
// Backport for macOS 11
|
||||
func data(from url: URL) async throws -> (Data, URLResponse) {
|
||||
try await withCheckedThrowingContinuation { continuation in
|
||||
URLSession.shared.dataTask(with: url) { data, response, error in
|
||||
guard let data = data, let response = response else {
|
||||
continuation.resume(throwing: error ?? NSError(domain: NSURLErrorDomain, code: NSURLErrorUnknown, userInfo: nil))
|
||||
return
|
||||
}
|
||||
continuation.resume(returning: (data, response))
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
}
|
||||
|
@ -4,9 +4,9 @@ import Foundation
|
||||
public protocol UpdaterProtocol: ObservableObject {
|
||||
|
||||
/// The latest update
|
||||
@MainActor var update: Release? { get }
|
||||
var update: Release? { get }
|
||||
/// A boolean describing whether or not the current build of the app is a "test" build (ie, a debug build or otherwise special build)
|
||||
@MainActor var testBuild: Bool { get }
|
||||
var testBuild: Bool { get }
|
||||
|
||||
}
|
||||
|
||||
|
@ -11,15 +11,18 @@ public class Agent {
|
||||
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.agent", category: "")
|
||||
|
||||
/// 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)
|
||||
}
|
||||
|
||||
}
|
||||
@ -30,40 +33,45 @@ extension Agent {
|
||||
/// - Parameters:
|
||||
/// - reader: A ``FileHandleReader`` to read the content of the request.
|
||||
/// - writer: A ``FileHandleWriter`` to write the response to.
|
||||
public func handle(reader: FileHandleReader, writer: FileHandleWriter) {
|
||||
Logger().debug("Agent handling new data")
|
||||
/// - Return value:
|
||||
/// - Boolean if data could be read
|
||||
@discardableResult public func handle(reader: FileHandleReader, writer: FileHandleWriter) -> Bool {
|
||||
logger.debug("Agent handling new data")
|
||||
let data = Data(reader.availableData)
|
||||
guard data.count > 4 else { return }
|
||||
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)")
|
||||
return
|
||||
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)
|
||||
writer.write(response)
|
||||
return true
|
||||
}
|
||||
|
||||
func handle(requestType: SSHAgent.RequestType, data: Data, reader: FileHandleReader) -> Data {
|
||||
// Depending on the launch context (such as after macOS update), the agent may need to reload secrets before acting
|
||||
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)")
|
||||
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
|
||||
@ -76,18 +84,29 @@ 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)
|
||||
let secrets = storeList.allSecrets
|
||||
certificateHandler.reloadCertificates(for: secrets)
|
||||
var count = UInt32(secrets.count).bigEndian
|
||||
let countData = Data(bytes: &count, count: UInt32.bitWidth/8)
|
||||
var keyData = Data()
|
||||
let writer = OpenSSHKeyWriter()
|
||||
|
||||
for secret in secrets {
|
||||
let keyBlob = writer.data(secret: secret)
|
||||
let keyBlob: Data
|
||||
let curveData: Data
|
||||
|
||||
if let (certificateData, name) = try? certificateHandler.keyBlobAndName(for: secret) {
|
||||
keyBlob = certificateData
|
||||
curveData = name
|
||||
} else {
|
||||
keyBlob = writer.data(secret: secret)
|
||||
curveData = writer.curveType(for: secret.algorithm, length: secret.keySize).data(using: .utf8)!
|
||||
}
|
||||
|
||||
keyData.append(writer.lengthAndData(of: keyBlob))
|
||||
let curveData = writer.curveType(for: secret.algorithm, length: secret.keySize).data(using: .utf8)!
|
||||
keyData.append(writer.lengthAndData(of: curveData))
|
||||
|
||||
}
|
||||
Logger().debug("Agent enumerated \(secrets.count) identities")
|
||||
logger.log("Agent enumerated \(secrets.count) identities")
|
||||
return countData + keyData
|
||||
}
|
||||
|
||||
@ -98,9 +117,17 @@ extension Agent {
|
||||
/// - Returns: An OpenSSH formatted Data payload containing the signed data response.
|
||||
func sign(data: Data, provenance: SigningRequestProvenance) 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
|
||||
}
|
||||
|
||||
@ -110,7 +137,7 @@ extension Agent {
|
||||
|
||||
let dataToSign = reader.readNextChunk()
|
||||
let signed = try store.sign(data: dataToSign, with: secret, for: provenance)
|
||||
let derSignature = signed.data
|
||||
let derSignature = signed
|
||||
|
||||
let curveData = writer.curveType(for: secret.algorithm, length: secret.keySize).data(using: .utf8)!
|
||||
|
||||
@ -151,10 +178,10 @@ extension Agent {
|
||||
signedData.append(writer.lengthAndData(of: sub))
|
||||
|
||||
if let witness = witness {
|
||||
try witness.witness(accessTo: secret, from: store, by: provenance, requiredAuthentication: signed.requiredAuthentication)
|
||||
try witness.witness(accessTo: secret, from: store, by: provenance)
|
||||
}
|
||||
|
||||
Logger().debug("Agent signed request")
|
||||
logger.debug("Agent signed request")
|
||||
|
||||
return signedData
|
||||
}
|
||||
@ -163,6 +190,16 @@ extension Agent {
|
||||
|
||||
extension Agent {
|
||||
|
||||
/// Gives any store with no loaded secrets a chance to reload.
|
||||
func reloadSecretsIfNeccessary() {
|
||||
for store in storeList.stores {
|
||||
if store.secrets.isEmpty {
|
||||
logger.debug("Store \(store.name, privacy: .public) has no loaded secrets. Reloading.")
|
||||
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.
|
||||
@ -188,6 +225,7 @@ extension Agent {
|
||||
case unhandledType
|
||||
case noMatchingKey
|
||||
case unsupportedKeyType
|
||||
case notOpenSSHCertificate
|
||||
}
|
||||
|
||||
}
|
||||
|
@ -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:
|
||||
|
@ -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)
|
||||
|
@ -17,7 +17,6 @@ public protocol SigningWitness {
|
||||
/// - 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.
|
||||
/// - requiredAuthentication: A boolean describing whether or not authentication was required for the request.
|
||||
func witness(accessTo secret: AnySecret, from store: AnySecretStore, by provenance: SigningRequestProvenance, requiredAuthentication: Bool) throws
|
||||
func witness(accessTo secret: AnySecret, from store: AnySecretStore, by provenance: SigningRequestProvenance) throws
|
||||
|
||||
}
|
||||
|
@ -9,7 +9,9 @@ public class SocketController {
|
||||
/// The active SocketPort.
|
||||
private var port: SocketPort?
|
||||
/// A handler that will be notified when a new read/write handle is available.
|
||||
public var handler: ((FileHandleReader, FileHandleWriter) -> Void)?
|
||||
/// False if no data could be read
|
||||
public var handler: ((FileHandleReader, FileHandleWriter) -> Bool)?
|
||||
|
||||
|
||||
/// Initializes a socket controller with a specified path.
|
||||
/// - Parameter path: The path to use as a socket.
|
||||
@ -65,7 +67,7 @@ public class SocketController {
|
||||
@objc func handleConnectionAccept(notification: Notification) {
|
||||
Logger().debug("Socket controller accepted connection")
|
||||
guard let new = notification.userInfo?[NSFileHandleNotificationFileHandleItem] as? FileHandle else { return }
|
||||
handler?(new, new)
|
||||
_ = handler?(new, new)
|
||||
new.waitForDataInBackgroundAndNotify()
|
||||
fileHandle?.acceptConnectionInBackgroundAndNotify(forModes: [RunLoop.current.currentMode!])
|
||||
}
|
||||
@ -76,7 +78,12 @@ public class SocketController {
|
||||
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")
|
||||
handler?(new, new)
|
||||
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")
|
||||
}
|
||||
}
|
||||
|
||||
}
|
||||
|
@ -27,5 +27,8 @@ SecretKit is a collection of protocols describing secrets and stores.
|
||||
|
||||
### Signing Process
|
||||
|
||||
- ``SignedData``
|
||||
- ``SigningRequestProvenance``
|
||||
|
||||
### Authentication Persistence
|
||||
|
||||
- ``PersistedAuthenticationContext``
|
||||
|
@ -9,6 +9,7 @@ public struct AnySecret: Secret {
|
||||
private let _name: () -> String
|
||||
private let _algorithm: () -> Algorithm
|
||||
private let _keySize: () -> Int
|
||||
private let _requiresAuthentication: () -> Bool
|
||||
private let _publicKey: () -> Data
|
||||
|
||||
public init<T>(_ secret: T) where T: Secret {
|
||||
@ -19,6 +20,7 @@ public struct AnySecret: Secret {
|
||||
_name = secret._name
|
||||
_algorithm = secret._algorithm
|
||||
_keySize = secret._keySize
|
||||
_requiresAuthentication = secret._requiresAuthentication
|
||||
_publicKey = secret._publicKey
|
||||
} else {
|
||||
base = secret as Any
|
||||
@ -27,6 +29,7 @@ public struct AnySecret: Secret {
|
||||
_name = { secret.name }
|
||||
_algorithm = { secret.algorithm }
|
||||
_keySize = { secret.keySize }
|
||||
_requiresAuthentication = { secret.requiresAuthentication }
|
||||
_publicKey = { secret.publicKey }
|
||||
}
|
||||
}
|
||||
@ -47,6 +50,10 @@ public struct AnySecret: Secret {
|
||||
_keySize()
|
||||
}
|
||||
|
||||
public var requiresAuthentication: Bool {
|
||||
_requiresAuthentication()
|
||||
}
|
||||
|
||||
public var publicKey: Data {
|
||||
_publicKey()
|
||||
}
|
||||
|
@ -9,8 +9,10 @@ public class AnySecretStore: SecretStore {
|
||||
private let _id: () -> UUID
|
||||
private let _name: () -> String
|
||||
private let _secrets: () -> [AnySecret]
|
||||
private let _sign: (Data, AnySecret, SigningRequestProvenance) throws -> SignedData
|
||||
private let _sign: (Data, AnySecret, SigningRequestProvenance) throws -> Data
|
||||
private let _existingPersistedAuthenticationContext: (AnySecret) -> PersistedAuthenticationContext?
|
||||
private let _persistAuthentication: (AnySecret, TimeInterval) throws -> Void
|
||||
private let _reloadSecrets: () -> Void
|
||||
|
||||
private var sink: AnyCancellable?
|
||||
|
||||
@ -21,7 +23,9 @@ public class AnySecretStore: SecretStore {
|
||||
_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) }
|
||||
_reloadSecrets = { secretStore.reloadSecrets() }
|
||||
sink = secretStore.objectWillChange.sink { _ in
|
||||
self.objectWillChange.send()
|
||||
}
|
||||
@ -43,14 +47,22 @@ public class AnySecretStore: SecretStore {
|
||||
return _secrets()
|
||||
}
|
||||
|
||||
public func sign(data: Data, with secret: AnySecret, for provenance: SigningRequestProvenance) throws -> SignedData {
|
||||
public func sign(data: Data, with secret: AnySecret, for provenance: SigningRequestProvenance) throws -> Data {
|
||||
try _sign(data, secret, provenance)
|
||||
}
|
||||
|
||||
public func existingPersistedAuthenticationContext(secret: AnySecret) -> PersistedAuthenticationContext? {
|
||||
_existingPersistedAuthenticationContext(secret)
|
||||
}
|
||||
|
||||
public func persistAuthentication(secret: AnySecret, forDuration duration: TimeInterval) throws {
|
||||
try _persistAuthentication(secret, duration)
|
||||
}
|
||||
|
||||
public func reloadSecrets() {
|
||||
_reloadSecrets()
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
public class AnySecretStoreModifiable: AnySecretStore, SecretStoreModifiable {
|
||||
|
@ -0,0 +1,120 @@
|
||||
import Foundation
|
||||
import OSLog
|
||||
|
||||
/// Manages storage and lookup for OpenSSH certificates.
|
||||
public class OpenSSHCertificateHandler {
|
||||
|
||||
private let publicKeyFileStoreController = PublicKeyFileStoreController(homeDirectory: NSHomeDirectory())
|
||||
private let logger = Logger()
|
||||
private let writer = OpenSSHKeyWriter()
|
||||
private var keyBlobsAndNames: [AnySecret: (Data, Data)] = [:]
|
||||
|
||||
/// 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 = 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[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[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"
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
}
|
@ -6,6 +6,7 @@ public class PublicKeyFileStoreController {
|
||||
|
||||
private let logger = Logger()
|
||||
private let directory: String
|
||||
private let keyWriter = OpenSSHKeyWriter()
|
||||
|
||||
/// Initializes a PublicKeyFileStoreController.
|
||||
public init(homeDirectory: String) {
|
||||
@ -14,16 +15,21 @@ 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 untracked = Set(try FileManager.default.contentsOfDirectory(atPath: directory)
|
||||
.map { "\(directory)/\($0)" })
|
||||
.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)
|
||||
let keyWriter = OpenSSHKeyWriter()
|
||||
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,8 +40,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 {
|
||||
directory.appending("/").appending("\(secret.name.replacingOccurrences(of: " ", with: "-")).pub")
|
||||
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")
|
||||
}
|
||||
|
||||
}
|
||||
|
@ -31,6 +31,10 @@ public class SecretStoreList: ObservableObject {
|
||||
stores.reduce(false, { $0 || $1.isAvailable })
|
||||
}
|
||||
|
||||
public var allSecrets: [AnySecret] {
|
||||
stores.flatMap(\.secrets)
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
extension SecretStoreList {
|
||||
|
@ -0,0 +1,9 @@
|
||||
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 {
|
||||
/// Whether the context remains valid.
|
||||
var valid: Bool { get }
|
||||
/// The date at which the authorization expires and the context becomes invalid.
|
||||
var expiration: Date { get }
|
||||
}
|
@ -9,6 +9,8 @@ public protocol Secret: Identifiable, Hashable {
|
||||
var algorithm: Algorithm { get }
|
||||
/// The key size for the secret.
|
||||
var keySize: Int { get }
|
||||
/// Whether the secret requires authentication before use.
|
||||
var requiresAuthentication: Bool { get }
|
||||
/// The public key data for the secret.
|
||||
var publicKey: Data { get }
|
||||
|
||||
|
@ -20,8 +20,14 @@ public protocol SecretStore: ObservableObject, Identifiable {
|
||||
/// - data: The data to sign.
|
||||
/// - secret: The ``Secret`` to sign with.
|
||||
/// - provenance: A ``SigningRequestProvenance`` describing where the request came from.
|
||||
/// - Returns: A ``SignedData`` object, containing the signature and metadata about the signature process.
|
||||
func sign(data: Data, with secret: SecretType, for provenance: SigningRequestProvenance) throws -> SignedData
|
||||
/// - Returns: The signed data.
|
||||
func sign(data: Data, with secret: SecretType, for provenance: SigningRequestProvenance) throws -> Data
|
||||
|
||||
/// 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?
|
||||
|
||||
/// Persists user authorization for access to a secret.
|
||||
/// - Parameters:
|
||||
@ -30,6 +36,9 @@ public protocol SecretStore: ObservableObject, Identifiable {
|
||||
/// - 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
|
||||
|
||||
/// Requests that the store reload secrets from any backing store, if neccessary.
|
||||
func reloadSecrets()
|
||||
|
||||
}
|
||||
|
||||
/// A SecretStore that the Secretive admin app can modify.
|
||||
@ -56,6 +65,9 @@ public protocol SecretStoreModifiable: SecretStore {
|
||||
|
||||
extension NSNotification.Name {
|
||||
|
||||
// Distributed notification that keys were modified out of process (ie, that the management tool added/removed secrets)
|
||||
public static let secretStoreUpdated = NSNotification.Name("com.maxgoedjen.Secretive.secretStore.updated")
|
||||
// Internal notification that keys were reloaded from the backing store.
|
||||
public static let secretStoreReloaded = NSNotification.Name("com.maxgoedjen.Secretive.secretStore.reloaded")
|
||||
|
||||
}
|
||||
|
@ -1,20 +0,0 @@
|
||||
import Foundation
|
||||
|
||||
/// Describes the output of a sign request.
|
||||
public struct SignedData {
|
||||
|
||||
/// The signed data.
|
||||
public let data: Data
|
||||
/// A boolean describing whether authentication was required during the signature process.
|
||||
public let requiredAuthentication: Bool
|
||||
|
||||
/// Initializes a new SignedData.
|
||||
/// - Parameters:
|
||||
/// - data: The signed data.
|
||||
/// - requiredAuthentication: A boolean describing whether authentication was required during the signature process.
|
||||
public init(data: Data, requiredAuthentication: Bool) {
|
||||
self.data = data
|
||||
self.requiredAuthentication = requiredAuthentication
|
||||
}
|
||||
|
||||
}
|
@ -11,6 +11,7 @@ extension SecureEnclave {
|
||||
public let name: String
|
||||
public let algorithm = Algorithm.ellipticCurve
|
||||
public let keySize = 256
|
||||
public let requiresAuthentication: Bool
|
||||
public let publicKey: Data
|
||||
|
||||
}
|
||||
|
@ -24,7 +24,7 @@ extension SecureEnclave {
|
||||
/// Initializes a Store.
|
||||
public init() {
|
||||
DistributedNotificationCenter.default().addObserver(forName: .secretStoreUpdated, object: nil, queue: .main) { _ in
|
||||
self.reloadSecrets(notify: false)
|
||||
self.reloadSecretsInternal(notifyAgent: false)
|
||||
}
|
||||
loadSecrets()
|
||||
}
|
||||
@ -68,7 +68,7 @@ extension SecureEnclave {
|
||||
throw KeychainError(statusCode: nil)
|
||||
}
|
||||
try savePublicKey(publicKey, name: name)
|
||||
reloadSecrets()
|
||||
reloadSecretsInternal()
|
||||
}
|
||||
|
||||
public func delete(secret: Secret) throws {
|
||||
@ -80,7 +80,7 @@ extension SecureEnclave {
|
||||
if status != errSecSuccess {
|
||||
throw KeychainError(statusCode: status)
|
||||
}
|
||||
reloadSecrets()
|
||||
reloadSecretsInternal()
|
||||
}
|
||||
|
||||
public func update(secret: Secret, name: String) throws {
|
||||
@ -97,10 +97,10 @@ extension SecureEnclave {
|
||||
if status != errSecSuccess {
|
||||
throw KeychainError(statusCode: status)
|
||||
}
|
||||
reloadSecrets()
|
||||
reloadSecretsInternal()
|
||||
}
|
||||
|
||||
public func sign(data: Data, with secret: SecretType, for provenance: SigningRequestProvenance) throws -> SignedData {
|
||||
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
|
||||
@ -131,16 +131,15 @@ extension SecureEnclave {
|
||||
let key = untypedSafe as! SecKey
|
||||
var signError: SecurityError?
|
||||
|
||||
let signingStartTime = Date()
|
||||
guard let signature = SecKeyCreateSignature(key, .ecdsaSignatureMessageX962SHA256, data as CFData, &signError) else {
|
||||
throw SigningError(error: signError)
|
||||
}
|
||||
let signatureDuration = Date().timeIntervalSince(signingStartTime)
|
||||
// Hack to determine if the user had to authenticate to sign.
|
||||
// Since there's now way to inspect SecAccessControl to determine (afaict).
|
||||
let requiredAuthentication = signatureDuration > Constants.unauthenticatedThreshold
|
||||
return signature as Data
|
||||
}
|
||||
|
||||
return SignedData(data: signature as Data, requiredAuthentication: requiredAuthentication)
|
||||
public func existingPersistedAuthenticationContext(secret: Secret) -> PersistedAuthenticationContext? {
|
||||
guard let persisted = persistedAuthenticationContexts[secret], persisted.valid else { return nil }
|
||||
return persisted
|
||||
}
|
||||
|
||||
public func persistAuthentication(secret: Secret, forDuration duration: TimeInterval) throws {
|
||||
@ -164,6 +163,10 @@ extension SecureEnclave {
|
||||
}
|
||||
}
|
||||
|
||||
public func reloadSecrets() {
|
||||
reloadSecretsInternal(notifyAgent: false)
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
}
|
||||
@ -171,18 +174,22 @@ extension SecureEnclave {
|
||||
extension SecureEnclave.Store {
|
||||
|
||||
/// Reloads all secrets from the store.
|
||||
/// - Parameter notify: A boolean indicating whether a distributed notification should be posted, notifying other processes (ie, the SecretAgent) to reload their stores as well.
|
||||
private func reloadSecrets(notify: Bool = true) {
|
||||
/// - 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 reloadSecretsInternal(notifyAgent: Bool = true) {
|
||||
let before = secrets
|
||||
secrets.removeAll()
|
||||
loadSecrets()
|
||||
if notify {
|
||||
DistributedNotificationCenter.default().post(name: .secretStoreUpdated, object: nil)
|
||||
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 attributes = [
|
||||
let publicAttributes = [
|
||||
kSecClass: kSecClassKey,
|
||||
kSecAttrKeyType: SecureEnclave.Constants.keyType,
|
||||
kSecAttrApplicationTag: SecureEnclave.Constants.keyTag,
|
||||
@ -191,16 +198,46 @@ extension SecureEnclave.Store {
|
||||
kSecMatchLimit: kSecMatchLimitAll,
|
||||
kSecReturnAttributes: true
|
||||
] as CFDictionary
|
||||
var untyped: CFTypeRef?
|
||||
SecItemCopyMatching(attributes, &untyped)
|
||||
guard let typed = untyped as? [[CFString: Any]] else { return }
|
||||
let wrapped: [SecureEnclave.Secret] = typed.map {
|
||||
var publicUntyped: CFTypeRef?
|
||||
SecItemCopyMatching(publicAttributes, &publicUntyped)
|
||||
guard let publicTyped = publicUntyped as? [[CFString: Any]] else { return }
|
||||
let privateAttributes = [
|
||||
kSecClass: kSecClassKey,
|
||||
kSecAttrKeyType: SecureEnclave.Constants.keyType,
|
||||
kSecAttrApplicationTag: SecureEnclave.Constants.keyTag,
|
||||
kSecAttrKeyClass: kSecAttrKeyClassPrivate,
|
||||
kSecReturnRef: true,
|
||||
kSecMatchLimit: kSecMatchLimitAll,
|
||||
kSecReturnAttributes: true
|
||||
] as CFDictionary
|
||||
var privateUntyped: CFTypeRef?
|
||||
SecItemCopyMatching(privateAttributes, &privateUntyped)
|
||||
guard let privateTyped = privateUntyped as? [[CFString: Any]] else { return }
|
||||
let privateMapped = privateTyped.reduce(into: [:] as [Data: [CFString: Any]]) { partialResult, next in
|
||||
let id = next[kSecAttrApplicationLabel] as! Data
|
||||
partialResult[id] = next
|
||||
}
|
||||
let authNotRequiredAccessControl: SecAccessControl =
|
||||
SecAccessControlCreateWithFlags(kCFAllocatorDefault,
|
||||
kSecAttrAccessibleWhenUnlockedThisDeviceOnly,
|
||||
[.privateKeyUsage],
|
||||
nil)!
|
||||
|
||||
let wrapped: [SecureEnclave.Secret] = publicTyped.map {
|
||||
let name = $0[kSecAttrLabel] as? String ?? "Unnamed"
|
||||
let id = $0[kSecAttrApplicationLabel] as! Data
|
||||
let publicKeyRef = $0[kSecValueRef] as! SecKey
|
||||
let publicKeyAttributes = SecKeyCopyAttributes(publicKeyRef) as! [CFString: Any]
|
||||
let publicKey = publicKeyAttributes[kSecValueData] as! Data
|
||||
return SecureEnclave.Secret(id: id, name: name, publicKey: publicKey)
|
||||
let privateKey = privateMapped[id]
|
||||
let requiresAuth: Bool
|
||||
if let authRequirements = privateKey?[kSecAttrAccessControl] {
|
||||
// Unfortunately we can't inspect the access control object directly, but it does behave predicatable with equality.
|
||||
requiresAuth = authRequirements as! SecAccessControl != authNotRequiredAccessControl
|
||||
} else {
|
||||
requiresAuth = false
|
||||
}
|
||||
return SecureEnclave.Secret(id: id, name: name, requiresAuthentication: requiresAuth, publicKey: publicKey)
|
||||
}
|
||||
secrets.append(contentsOf: wrapped)
|
||||
}
|
||||
@ -263,7 +300,7 @@ extension SecureEnclave {
|
||||
extension SecureEnclave {
|
||||
|
||||
/// A context describing a persisted authentication.
|
||||
private struct PersistentAuthenticationContext {
|
||||
private struct PersistentAuthenticationContext: PersistedAuthenticationContext {
|
||||
|
||||
/// The Secret to persist authentication for.
|
||||
let secret: Secret
|
||||
@ -271,7 +308,7 @@ extension SecureEnclave {
|
||||
let context: LAContext
|
||||
/// An expiration date for the context.
|
||||
/// - Note - Monotonic time instead of Date() to prevent people setting the clock back.
|
||||
let expiration: UInt64
|
||||
let monotonicExpiration: UInt64
|
||||
|
||||
/// Initializes a context.
|
||||
/// - Parameters:
|
||||
@ -282,12 +319,18 @@ extension SecureEnclave {
|
||||
self.secret = secret
|
||||
self.context = context
|
||||
let durationInNanoSeconds = Measurement(value: duration, unit: UnitDuration.seconds).converted(to: .nanoseconds).value
|
||||
self.expiration = clock_gettime_nsec_np(CLOCK_MONOTONIC) + UInt64(durationInNanoSeconds)
|
||||
self.monotonicExpiration = clock_gettime_nsec_np(CLOCK_MONOTONIC) + UInt64(durationInNanoSeconds)
|
||||
}
|
||||
|
||||
/// A boolean describing whether or not the context is still valid.
|
||||
var valid: Bool {
|
||||
clock_gettime_nsec_np(CLOCK_MONOTONIC) < expiration
|
||||
clock_gettime_nsec_np(CLOCK_MONOTONIC) < monotonicExpiration
|
||||
}
|
||||
|
||||
var expiration: Date {
|
||||
let remainingNanoseconds = monotonicExpiration - clock_gettime_nsec_np(CLOCK_MONOTONIC)
|
||||
let remainingInSeconds = Measurement(value: Double(remainingNanoseconds), unit: UnitDuration.nanoseconds).converted(to: .seconds).value
|
||||
return Date(timeIntervalSinceNow: remainingInSeconds)
|
||||
}
|
||||
}
|
||||
|
||||
|
@ -11,6 +11,7 @@ extension SmartCard {
|
||||
public let name: String
|
||||
public let algorithm: Algorithm
|
||||
public let keySize: Int
|
||||
public let requiresAuthentication: Bool = false
|
||||
public let publicKey: Data
|
||||
|
||||
}
|
||||
|
@ -44,7 +44,7 @@ extension SmartCard {
|
||||
fatalError("Keys must be deleted on the smart card.")
|
||||
}
|
||||
|
||||
public func sign(data: Data, with secret: SecretType, for provenance: SigningRequestProvenance) throws -> SignedData {
|
||||
public func sign(data: Data, with secret: SecretType, for provenance: SigningRequestProvenance) throws -> Data {
|
||||
guard let tokenID = tokenID else { fatalError() }
|
||||
let context = LAContext()
|
||||
context.localizedReason = "sign a request from \"\(provenance.origin.displayName)\" using secret \"\(secret.name)\""
|
||||
@ -79,12 +79,29 @@ extension SmartCard {
|
||||
guard let signature = SecKeyCreateSignature(key, signatureAlgorithm, data as CFData, &signError) else {
|
||||
throw SigningError(error: signError)
|
||||
}
|
||||
return SignedData(data: signature as Data, requiredAuthentication: false)
|
||||
return signature as Data
|
||||
}
|
||||
|
||||
public func existingPersistedAuthenticationContext(secret: SmartCard.Secret) -> PersistedAuthenticationContext? {
|
||||
nil
|
||||
}
|
||||
|
||||
public func persistAuthentication(secret: SmartCard.Secret, forDuration: TimeInterval) throws {
|
||||
}
|
||||
|
||||
/// Reloads all secrets from the store.
|
||||
public func reloadSecrets() {
|
||||
DispatchQueue.main.async {
|
||||
self.isAvailable = self.tokenID != nil
|
||||
let before = self.secrets
|
||||
self.secrets.removeAll()
|
||||
self.loadSecrets()
|
||||
if self.secrets != before {
|
||||
NotificationCenter.default.post(name: .secretStoreReloaded, object: self)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
}
|
||||
@ -98,15 +115,6 @@ extension SmartCard.Store {
|
||||
reloadSecrets()
|
||||
}
|
||||
|
||||
/// Reloads all secrets from the store.
|
||||
private func reloadSecrets() {
|
||||
DispatchQueue.main.async {
|
||||
self.isAvailable = self.tokenID != nil
|
||||
self.secrets.removeAll()
|
||||
self.loadSecrets()
|
||||
}
|
||||
}
|
||||
|
||||
/// Loads all secrets from the store.
|
||||
private func loadSecrets() {
|
||||
guard let tokenID = tokenID else { return }
|
||||
|
@ -49,7 +49,7 @@ extension Stub {
|
||||
print("Public Key OpenSSH: \(OpenSSHKeyWriter().openSSHString(secret: secret))")
|
||||
}
|
||||
|
||||
public func sign(data: Data, with secret: Secret, for provenance: SigningRequestProvenance) throws -> SignedData {
|
||||
public func sign(data: Data, with secret: Secret, for provenance: SigningRequestProvenance) throws -> Data {
|
||||
guard !shouldThrow else {
|
||||
throw NSError(domain: "test", code: 0, userInfo: nil)
|
||||
}
|
||||
@ -68,12 +68,19 @@ extension Stub {
|
||||
default:
|
||||
fatalError()
|
||||
}
|
||||
return SignedData(data: SecKeyCreateSignature(privateKey, signatureAlgorithm, data as CFData, nil)! as Data, requiredAuthentication: false)
|
||||
return SecKeyCreateSignature(privateKey, signatureAlgorithm, data as CFData, nil)! as Data
|
||||
}
|
||||
|
||||
public func existingPersistedAuthenticationContext(secret: Stub.Secret) -> PersistedAuthenticationContext? {
|
||||
nil
|
||||
}
|
||||
|
||||
public func persistAuthentication(secret: Stub.Secret, forDuration duration: TimeInterval) throws {
|
||||
}
|
||||
|
||||
public func reloadSecrets() {
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
}
|
||||
@ -88,6 +95,7 @@ extension Stub {
|
||||
|
||||
let keySize: Int
|
||||
let publicKey: Data
|
||||
let requiresAuthentication = false
|
||||
let privateKey: Data
|
||||
|
||||
init(keySize: Int, publicKey: Data, privateKey: Data) {
|
||||
|
@ -17,7 +17,7 @@ func speakNowOrForeverHoldYourPeace(forAccessTo secret: AnySecret, from store: A
|
||||
}
|
||||
}
|
||||
|
||||
func witness(accessTo secret: AnySecret, from store: AnySecretStore, by provenance: SigningRequestProvenance, requiredAuthentication: Bool) throws {
|
||||
func witness(accessTo secret: AnySecret, from store: AnySecretStore, by provenance: SigningRequestProvenance) throws {
|
||||
witness(secret, provenance)
|
||||
}
|
||||
|
||||
|
@ -16,7 +16,7 @@ class AppDelegate: NSObject, NSApplicationDelegate {
|
||||
list.add(store: SmartCard.Store())
|
||||
return list
|
||||
}()
|
||||
private let updater = Updater()
|
||||
private let updater = Updater(checkOnLaunch: false)
|
||||
private let notifier = Notifier()
|
||||
private let publicKeyFileStoreController = PublicKeyFileStoreController(homeDirectory: NSHomeDirectory())
|
||||
private lazy var agent: Agent = {
|
||||
@ -33,15 +33,15 @@ class AppDelegate: NSObject, NSApplicationDelegate {
|
||||
DispatchQueue.main.async {
|
||||
self.socketController.handler = self.agent.handle(reader:writer:)
|
||||
}
|
||||
DistributedNotificationCenter.default().addObserver(forName: .secretStoreUpdated, object: nil, queue: .main) { [self] _ in
|
||||
try? publicKeyFileStoreController.generatePublicKeys(for: storeList.stores.flatMap({ $0.secrets }), clear: true)
|
||||
NotificationCenter.default.addObserver(forName: .secretStoreReloaded, object: nil, queue: .main) { [self] _ in
|
||||
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:))
|
||||
// }
|
||||
updateSink = updater.$update.sink { update in
|
||||
guard let update = update else { return }
|
||||
self.notifier.notify(update: update, ignore: self.updater.ignore(release:))
|
||||
}
|
||||
}
|
||||
|
||||
}
|
||||
|
@ -57,7 +57,7 @@ class Notifier {
|
||||
notificationCenter.requestAuthorization(options: .alert) { _, _ in }
|
||||
}
|
||||
|
||||
func notify(accessTo secret: AnySecret, from store: AnySecretStore, by provenance: SigningRequestProvenance, requiredAuthentication: Bool) {
|
||||
func notify(accessTo secret: AnySecret, from store: AnySecretStore, by provenance: SigningRequestProvenance) {
|
||||
notificationDelegate.pendingPersistableSecrets[secret.id.description] = secret
|
||||
notificationDelegate.pendingPersistableStores[store.id.description] = store
|
||||
let notificationCenter = UNUserNotificationCenter.current()
|
||||
@ -69,7 +69,7 @@ class Notifier {
|
||||
if #available(macOS 12.0, *) {
|
||||
notificationContent.interruptionLevel = .timeSensitive
|
||||
}
|
||||
if requiredAuthentication {
|
||||
if secret.requiresAuthentication && store.existingPersistedAuthenticationContext(secret: secret) == nil {
|
||||
notificationContent.categoryIdentifier = Constants.persistAuthenticationCategoryIdentitifier
|
||||
}
|
||||
if let iconURL = provenance.origin.iconURL, let attachment = try? UNNotificationAttachment(identifier: "icon", url: iconURL, options: nil) {
|
||||
@ -106,8 +106,8 @@ extension Notifier: SigningWitness {
|
||||
func speakNowOrForeverHoldYourPeace(forAccessTo secret: AnySecret, from store: AnySecretStore, by provenance: SigningRequestProvenance) throws {
|
||||
}
|
||||
|
||||
func witness(accessTo secret: AnySecret, from store: AnySecretStore, by provenance: SigningRequestProvenance, requiredAuthentication: Bool) throws {
|
||||
notify(accessTo: secret, from: store, by: provenance, requiredAuthentication: requiredAuthentication)
|
||||
func witness(accessTo secret: AnySecret, from store: AnySecretStore, by provenance: SigningRequestProvenance) throws {
|
||||
notify(accessTo: secret, from: store, by: provenance)
|
||||
}
|
||||
|
||||
}
|
||||
@ -154,7 +154,7 @@ class NotificationDelegate: NSObject, UNUserNotificationCenterDelegate {
|
||||
case Notifier.Constants.persistAuthenticationCategoryIdentitifier:
|
||||
handlePersistAuthenticationResponse(response: response)
|
||||
default:
|
||||
fatalError()
|
||||
break
|
||||
}
|
||||
|
||||
completionHandler()
|
||||
|
@ -31,6 +31,7 @@
|
||||
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 */; };
|
||||
@ -123,6 +124,7 @@
|
||||
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>"; };
|
||||
@ -275,6 +277,7 @@
|
||||
50153E1F250AFCB200525160 /* UpdateView.swift */,
|
||||
5066A6C12516F303004B5A36 /* SetupView.swift */,
|
||||
5066A6C72516FE6E004B5A36 /* CopyableView.swift */,
|
||||
5065E312295517C500E16645 /* ToolbarButtonStyle.swift */,
|
||||
);
|
||||
path = Views;
|
||||
sourceTree = "<group>";
|
||||
@ -475,6 +478,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 */,
|
||||
|
@ -75,6 +75,7 @@
|
||||
ignoresPersistentStateOnLaunch = "NO"
|
||||
debugDocumentVersioning = "YES"
|
||||
debugServiceExtension = "internal"
|
||||
enableGPUValidationMode = "1"
|
||||
allowLocationSimulation = "YES">
|
||||
<BuildableProductRunnable
|
||||
runnableDebuggingMode = "0">
|
||||
|
@ -16,7 +16,6 @@ struct Secretive: App {
|
||||
}()
|
||||
private let agentStatusChecker = AgentStatusChecker()
|
||||
private let justUpdatedChecker = JustUpdatedChecker()
|
||||
private let updater = Updater()
|
||||
|
||||
@AppStorage("defaultsHasRunSetup") var hasRunSetup = false
|
||||
@State private var showingSetup = false
|
||||
@ -26,15 +25,11 @@ struct Secretive: App {
|
||||
WindowGroup {
|
||||
ContentView<Updater, AgentStatusChecker>(showingCreation: $showingCreation, runningSetup: $showingSetup, hasRunSetup: $hasRunSetup)
|
||||
.environmentObject(storeList)
|
||||
.environmentObject(updater)
|
||||
.environmentObject(Updater(checkOnLaunch: hasRunSetup))
|
||||
.environmentObject(agentStatusChecker)
|
||||
.onAppear {
|
||||
if !hasRunSetup {
|
||||
showingSetup = true
|
||||
} else {
|
||||
Task { [updater] in
|
||||
await updater.checkForUpdates()
|
||||
}
|
||||
}
|
||||
}
|
||||
.onReceive(NotificationCenter.default.publisher(for: NSApplication.didBecomeActiveNotification)) { _ in
|
||||
|
@ -6,6 +6,7 @@ import SecretKit
|
||||
protocol AgentStatusCheckerProtocol: ObservableObject {
|
||||
var running: Bool { get }
|
||||
var developmentBuild: Bool { get }
|
||||
func restart()
|
||||
}
|
||||
|
||||
class AgentStatusChecker: ObservableObject, AgentStatusCheckerProtocol {
|
||||
@ -37,12 +38,15 @@ class AgentStatusChecker: ObservableObject, AgentStatusCheckerProtocol {
|
||||
return nil
|
||||
}
|
||||
|
||||
|
||||
// Whether Secretive is being run in an Xcode environment.
|
||||
var developmentBuild: Bool {
|
||||
Bundle.main.bundleURL.absoluteString.contains("/Library/Developer/Xcode")
|
||||
}
|
||||
|
||||
func restart() {
|
||||
instanceSecretAgentProcess?.forceTerminate()
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
|
||||
|
@ -10,4 +10,7 @@ class PreviewAgentStatusChecker: AgentStatusCheckerProtocol {
|
||||
self.running = running
|
||||
}
|
||||
|
||||
func restart() {
|
||||
}
|
||||
|
||||
}
|
||||
|
@ -11,6 +11,7 @@ extension Preview {
|
||||
let name: String
|
||||
let algorithm = Algorithm.ellipticCurve
|
||||
let keySize = 256
|
||||
let requiresAuthentication: Bool = false
|
||||
let publicKey = UUID().uuidString.data(using: .utf8)!
|
||||
|
||||
}
|
||||
@ -35,13 +36,20 @@ extension Preview {
|
||||
self.secrets.append(contentsOf: new)
|
||||
}
|
||||
|
||||
func sign(data: Data, with secret: Preview.Secret, for provenance: SigningRequestProvenance) throws -> SignedData {
|
||||
return SignedData(data: data, requiredAuthentication: false)
|
||||
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 {
|
||||
}
|
||||
|
||||
func reloadSecrets() {
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
class StoreModifiable: Store, SecretStoreModifiable {
|
||||
|
@ -9,6 +9,8 @@ struct ContentView<UpdaterType: UpdaterProtocol, AgentStatusCheckerType: AgentSt
|
||||
@Binding var showingCreation: Bool
|
||||
@Binding var runningSetup: Bool
|
||||
@Binding var hasRunSetup: Bool
|
||||
@State var showingAgentInfo = false
|
||||
@Environment(\.colorScheme) var colorScheme
|
||||
|
||||
@EnvironmentObject private var storeList: SecretStoreList
|
||||
@EnvironmentObject private var updater: UpdaterType
|
||||
@ -27,10 +29,13 @@ struct ContentView<UpdaterType: UpdaterProtocol, AgentStatusCheckerType: AgentSt
|
||||
}
|
||||
.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)
|
||||
}
|
||||
}
|
||||
|
||||
@ -38,124 +43,144 @@ 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: (String, Color)? {
|
||||
guard let update = updater.update else { return nil }
|
||||
if update.critical {
|
||||
text = "Critical Security Update Required"
|
||||
color = .red
|
||||
return ("Critical Security Update Required", .red)
|
||||
} else {
|
||||
if updater.testBuild {
|
||||
text = "Test Build"
|
||||
color = .blue
|
||||
return ("Test Build", .blue)
|
||||
} else {
|
||||
text = "Update Available"
|
||||
color = .orange
|
||||
return ("Update Available", .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()
|
||||
}
|
||||
}
|
||||
.sheet(isPresented: $runningSetup) {
|
||||
SetupView(visible: $runningSetup, setupComplete: $hasRunSetup)
|
||||
}
|
||||
)
|
||||
}
|
||||
}
|
||||
|
||||
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: .point(.bottom), 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)
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@ViewBuilder
|
||||
var setupNoticeView: some View {
|
||||
Button(action: {
|
||||
runningSetup = true
|
||||
}, label: {
|
||||
Group {
|
||||
if hasRunSetup && !agentStatusChecker.running {
|
||||
Text("Secret Agent Is Not Running")
|
||||
} else {
|
||||
Text("Setup Secretive")
|
||||
}
|
||||
}
|
||||
.font(.headline)
|
||||
.foregroundColor(.white)
|
||||
})
|
||||
.buttonStyle(ToolbarButtonStyle(color: .orange))
|
||||
}
|
||||
|
||||
@ViewBuilder
|
||||
var runningNoticeView: some View {
|
||||
Button(action: {
|
||||
showingAgentInfo = true
|
||||
}, label: {
|
||||
HStack {
|
||||
Text("Agent is Running")
|
||||
.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: .point(.bottom), arrowEdge: .bottom) {
|
||||
VStack {
|
||||
Text("SecretAgent is Running")
|
||||
.font(.title)
|
||||
.padding(5)
|
||||
Text("SecretAgent is a process that runs in the background to sign requests, so you don't need to keep Secretive open all the time.\n\n**You can close Secretive, and everything will still keep working.**")
|
||||
.frame(width: 300)
|
||||
Button("Restart Agent") {
|
||||
self.agentStatusChecker.restart()
|
||||
}
|
||||
}
|
||||
.padding()
|
||||
}
|
||||
}
|
||||
|
||||
@ViewBuilder
|
||||
var appPathNoticeView: some View {
|
||||
if !ApplicationDirectoryController().isInApplicationsDirectory {
|
||||
Button(action: {
|
||||
showingAppPathNotice = true
|
||||
}, label: {
|
||||
Group {
|
||||
Text("Secretive Is Not in Applications Folder")
|
||||
}
|
||||
.font(.headline)
|
||||
.foregroundColor(.white)
|
||||
})
|
||||
.buttonStyle(ToolbarButtonStyle(color: .orange))
|
||||
.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()
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@ -198,3 +223,4 @@ struct ContentView_Previews: PreviewProvider {
|
||||
}
|
||||
|
||||
#endif
|
||||
|
||||
|
@ -8,6 +8,7 @@ struct CopyableView: View {
|
||||
var text: String
|
||||
|
||||
@State private var interactionState: InteractionState = .normal
|
||||
@Environment(\.colorScheme) private var colorScheme
|
||||
|
||||
var body: some View {
|
||||
VStack(alignment: .leading) {
|
||||
@ -77,38 +78,32 @@ struct CopyableView: View {
|
||||
}
|
||||
|
||||
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() {
|
||||
@ -128,7 +123,9 @@ struct CopyableView_Previews: PreviewProvider {
|
||||
static var previews: some View {
|
||||
Group {
|
||||
CopyableView(title: "Title", image: Image(systemName: "figure.wave"), text: "Hello world.")
|
||||
.padding()
|
||||
CopyableView(title: "Title", image: Image(systemName: "figure.wave"), text: "Long text. Long text. Long text. Long text. Long text. Long text. Long text. Long text. Long text. Long text. Long text. Long text. Long text. Long text. Long text. Long text. Long text. Long text. Long text. Long text. Long text. Long text. Long text. Long text. Long text. Long text. Long text. Long text. Long text. ")
|
||||
.padding()
|
||||
}
|
||||
}
|
||||
}
|
||||
|
@ -12,28 +12,35 @@ 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 a New Secret")
|
||||
.font(.largeTitle)
|
||||
Spacer()
|
||||
}
|
||||
HStack {
|
||||
Text("Name:")
|
||||
TextField("Shhhhh", text: $name).focusable()
|
||||
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)
|
||||
if #available(macOS 12.0, *) {
|
||||
ThumbnailPickerView(items: [
|
||||
ThumbnailPickerView.Item(value: true, name: "Require Authentication", description: "You will be required to authenticate using Touch ID, Apple Watch, or password before each use.", thumbnail: AuthenticationView()),
|
||||
ThumbnailPickerView.Item(value: false, name: "Notify",
|
||||
description: "No authentication is required while your Mac is unlocked, but you will be notified when a secret is used.",
|
||||
thumbnail: NotificationView())
|
||||
], selection: $requiresAuthentication)
|
||||
} else {
|
||||
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(minLength: 10)
|
||||
}
|
||||
.pickerStyle(RadioGroupPickerStyle())
|
||||
}
|
||||
Spacer()
|
||||
}
|
||||
}
|
||||
}
|
||||
@ -54,4 +61,208 @@ struct CreateSecretView<StoreType: SecretStoreModifiable>: View {
|
||||
try! 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<ValueType: Hashable>: Identifiable {
|
||||
let id = UUID()
|
||||
let value: ValueType
|
||||
let name: String
|
||||
let description: String
|
||||
let thumbnail: AnyView
|
||||
|
||||
init<ViewType: View>(value: ValueType, name: String, description: String, 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
|
||||
}
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
@available(macOS 12.0, *)
|
||||
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))
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@available(macOS 12.0, *)
|
||||
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("Touch ID Prompt")
|
||||
.font(.headline)
|
||||
.foregroundColor(.primary)
|
||||
.redacted(reason: .placeholder)
|
||||
VStack {
|
||||
Text("Touch ID Detail prompt.Detail two.")
|
||||
.font(.caption2)
|
||||
.foregroundColor(.primary)
|
||||
Text("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()
|
||||
|
||||
}
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
@available(macOS 12.0, *)
|
||||
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("Secretive")
|
||||
.font(.title)
|
||||
.foregroundColor(.primary)
|
||||
Text("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))
|
||||
if #available(macOS 12.0, *) {
|
||||
AuthenticationView().environment(\.colorScheme, .dark)
|
||||
AuthenticationView().environment(\.colorScheme, .light)
|
||||
NotificationView().environment(\.colorScheme, .dark)
|
||||
NotificationView().environment(\.colorScheme, .light)
|
||||
} else {
|
||||
// Fallback on earlier versions
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#endif
|
||||
|
@ -21,7 +21,7 @@ struct SecretDetailView<SecretType: Secret>: View {
|
||||
CopyableView(title: "Public Key", 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: "Public Key Path", image: Image(systemName: "lock.doc"), text: publicKeyFileStoreController.publicKeyPath(for: secret))
|
||||
Spacer()
|
||||
}
|
||||
}
|
||||
|
@ -20,7 +20,15 @@ struct SecretListItemView: View {
|
||||
)
|
||||
|
||||
return NavigationLink(destination: SecretDetailView(secret: secret), tag: secret.id, selection: $activeSecret) {
|
||||
Text(secret.name)
|
||||
if secret.requiresAuthentication {
|
||||
HStack {
|
||||
Text(secret.name)
|
||||
Spacer()
|
||||
Image(systemName: "lock")
|
||||
}
|
||||
} else {
|
||||
Text(secret.name)
|
||||
}
|
||||
}.contextMenu {
|
||||
if store is AnySecretStoreModifiable {
|
||||
Button(action: { isRenaming = true }) {
|
||||
|
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
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
@ -18,9 +18,7 @@ struct UpdateDetailView<UpdaterType: Updater>: View {
|
||||
HStack {
|
||||
if !update.critical {
|
||||
Button("Ignore") {
|
||||
Task { [updater, update] in
|
||||
await updater.ignore(release: update)
|
||||
}
|
||||
updater.ignore(release: update)
|
||||
}
|
||||
Spacer()
|
||||
}
|
||||
|
Reference in New Issue
Block a user