Compare commits

..

4 Commits

Author SHA1 Message Date
076c6dad26 Turn on enhanced security 2025-06-14 16:43:13 -07:00
697fdfafe4 Toolbar tweaks 2025-06-14 16:42:12 -07:00
d68c5a162c Fix shadowed type 2025-06-14 15:24:59 -07:00
6ca09f901f Add packages as explicit dependency. 2025-06-14 15:24:10 -07:00
52 changed files with 892 additions and 766 deletions

View File

@ -6,7 +6,7 @@ on:
jobs:
build:
# runs-on: macOS-latest
runs-on: macos-15
runs-on: macos-14
timeout-minutes: 10
steps:
- uses: actions/checkout@v4
@ -20,7 +20,7 @@ jobs:
APPLE_API_KEY_ID: ${{ secrets.APPLE_API_KEY_ID }}
run: ./.github/scripts/signing.sh
- name: Set Environment
run: sudo xcrun xcode-select -s /Applications/Xcode_16.2.app
run: sudo xcrun xcode-select -s /Applications/Xcode_15.4.app
- name: Update Build Number
env:
RUN_ID: ${{ github.run_id }}

View File

@ -7,7 +7,7 @@ on:
jobs:
test:
# runs-on: macOS-latest
runs-on: macos-15
runs-on: macos-14
timeout-minutes: 10
steps:
- uses: actions/checkout@v4
@ -21,7 +21,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_16.2.app
run: sudo xcrun xcode-select -s /Applications/Xcode_15.4.app
- name: Test
run: |
pushd Sources/Packages
@ -29,7 +29,7 @@ jobs:
popd
build:
# runs-on: macOS-latest
runs-on: macos-15
runs-on: macos-14
timeout-minutes: 10
steps:
- uses: actions/checkout@v4
@ -43,7 +43,7 @@ jobs:
APPLE_API_KEY_ID: ${{ secrets.APPLE_API_KEY_ID }}
run: ./.github/scripts/signing.sh
- name: Set Environment
run: sudo xcrun xcode-select -s /Applications/Xcode_16.2.app
run: sudo xcrun xcode-select -s /Applications/Xcode_15.4.app
- name: Update Build Number
env:
TAG_NAME: ${{ github.ref }}

View File

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

View File

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

View File

@ -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

View File

@ -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]

View File

@ -1,14 +1,10 @@
import Foundation
import Observation
import Synchronization
import Combine
/// A concrete implementation of ``UpdaterProtocol`` which considers the current release and OS version.
@Observable public final class Updater: UpdaterProtocol, ObservableObject, Sendable {
public final class Updater: ObservableObject, UpdaterProtocol {
public var update: Release? {
_update.withLock { $0 }
}
private let _update: Mutex<Release?> = .init(nil)
@Published public var update: Release?
public let testBuild: Bool
/// The current OS version.
@ -28,34 +24,30 @@ import Synchronization
testBuild = currentVersion == SemVer("0.0.0")
if checkOnLaunch {
// Don't do a launch check if the user hasn't seen the setup prompt explaining updater yet.
Task {
await checkForUpdates()
}
checkForUpdates()
}
Task {
while !Task.isCancelled {
try? await Task.sleep(for: .seconds(Int(checkFrequency)))
await checkForUpdates()
}
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) else { return }
guard 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 MainActor.run {
_update.withLock { value in
value = nil
}
DispatchQueue.main.async {
self.update = nil
}
}
@ -65,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()
@ -75,10 +67,8 @@ extension Updater {
guard !release.prerelease else { return }
let latestVersion = SemVer(release.name)
if latestVersion > currentVersion {
await MainActor.run {
_update.withLock { value in
value = release
}
DispatchQueue.main.async {
self.update = release
}
}
}

View File

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

View File

@ -5,7 +5,7 @@ import SecretKit
import AppKit
/// The `Agent` is an implementation of an SSH agent. It manages coordination and access between a socket, traces requests, notifies witnesses and passes requests to stores.
public final class Agent: Sendable {
public final class Agent {
private let storeList: SecretStoreList
private let witness: SigningWitness?
@ -54,7 +54,7 @@ extension Agent {
func handle(requestType: SSHAgent.RequestType, data: Data, reader: FileHandleReader) async -> Data {
// Depending on the launch context (such as after macOS update), the agent may need to reload secrets before acting
await reloadSecretsIfNeccessary()
reloadSecretsIfNeccessary()
var response = Data()
do {
switch requestType {
@ -65,7 +65,7 @@ extension Agent {
case .signRequest:
let provenance = requestTracer.provenance(from: reader)
response.append(SSHAgent.ResponseType.agentSignResponse.data)
response.append(try await sign(data: data, provenance: provenance))
response.append(try sign(data: data, provenance: provenance))
logger.debug("Agent returned \(SSHAgent.ResponseType.agentSignResponse.debugDescription)")
}
} catch {
@ -112,7 +112,7 @@ extension Agent {
/// - data: The data to sign.
/// - provenance: A ``SecretKit.SigningRequestProvenance`` object describing the origin of the request.
/// - Returns: An OpenSSH formatted Data payload containing the signed data response.
func sign(data: Data, provenance: SigningRequestProvenance) async throws -> Data {
func sign(data: Data, provenance: SigningRequestProvenance) throws -> Data {
let reader = OpenSSHReader(data: data)
let payloadHash = reader.readNextChunk()
let hash: Data
@ -129,11 +129,11 @@ extension Agent {
}
if let witness = witness {
try await witness.speakNowOrForeverHoldYourPeace(forAccessTo: secret, from: store, by: provenance)
try witness.speakNowOrForeverHoldYourPeace(forAccessTo: secret, from: store, by: provenance)
}
let dataToSign = reader.readNextChunk()
let signed = try await store.sign(data: dataToSign, with: secret, for: provenance)
let signed = try store.sign(data: dataToSign, with: secret, for: provenance)
let derSignature = signed
let curveData = writer.curveType(for: secret.algorithm, length: secret.keySize).data(using: .utf8)!
@ -175,7 +175,7 @@ extension Agent {
signedData.append(writer.lengthAndData(of: sub))
if let witness = witness {
try await witness.witness(accessTo: secret, from: store, by: provenance)
try witness.witness(accessTo: secret, from: store, by: provenance)
}
logger.debug("Agent signed request")
@ -188,11 +188,11 @@ extension Agent {
extension Agent {
/// Gives any store with no loaded secrets a chance to reload.
func reloadSecretsIfNeccessary() async {
func reloadSecretsIfNeccessary() {
for store in storeList.stores {
if store.secrets.isEmpty {
logger.debug("Store \(store.name, privacy: .public) has no loaded secrets. Reloading.")
await store.reloadSecrets()
store.reloadSecrets()
}
}
}

View File

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

View File

@ -1,7 +1,7 @@
import Foundation
/// Type eraser for Secret.
public struct AnySecret: Secret, @unchecked Sendable {
public struct AnySecret: Secret {
let base: Any
private let hashable: AnyHashable

View File

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

View File

@ -1,14 +1,13 @@
import Foundation
import OSLog
import Synchronization
/// Manages storage and lookup for OpenSSH certificates.
public final class OpenSSHCertificateHandler: Sendable {
public final class OpenSSHCertificateHandler {
private let publicKeyFileStoreController = PublicKeyFileStoreController(homeDirectory: NSHomeDirectory())
private let logger = Logger(subsystem: "com.maxgoedjen.secretive.secretagent", category: "OpenSSHCertificateHandler")
private let writer = OpenSSHKeyWriter()
private let keyBlobsAndNames: Mutex<[AnySecret: (Data, Data)]> = .init([:])
private var keyBlobsAndNames: [AnySecret: (Data, Data)] = [:]
/// Initializes an OpenSSHCertificateHandler.
public init() {
@ -21,10 +20,8 @@ public final class OpenSSHCertificateHandler: Sendable {
logger.log("No certificates, short circuiting")
return
}
keyBlobsAndNames.withLock {
$0 = secrets.reduce(into: [:]) { partialResult, next in
partialResult[next] = try? loadKeyblobAndName(for: next)
}
keyBlobsAndNames = secrets.reduce(into: [:]) { partialResult, next in
partialResult[next] = try? loadKeyblobAndName(for: next)
}
}
@ -32,10 +29,7 @@ public final class OpenSSHCertificateHandler: Sendable {
/// - Parameter secret: The secret to check for a certificate.
/// - Returns: A boolean describing whether or not the certificate handler has a certifiicate associated with a given secret
public func hasCertificate<SecretType: Secret>(for secret: SecretType) -> Bool {
keyBlobsAndNames.withLock {
$0[AnySecret(secret)] != nil
}
keyBlobsAndNames[AnySecret(secret)] != nil
}
@ -67,9 +61,7 @@ public final class OpenSSHCertificateHandler: Sendable {
/// - Parameter secret: The secret to search for a certificate with
/// - Returns: A (``Data``, ``Data``) tuple containing the certificate and certificate name, respectively.
public func keyBlobAndName<SecretType: Secret>(for secret: SecretType) throws -> (Data, Data)? {
keyBlobsAndNames.withLock {
$0[AnySecret(secret)]
}
keyBlobsAndNames[AnySecret(secret)]
}
/// Attempts to find an OpenSSH Certificate that corresponds to a ``Secret``

View File

@ -2,7 +2,7 @@ import Foundation
import CryptoKit
/// Generates OpenSSH representations of Secrets.
public struct OpenSSHKeyWriter: Sendable {
public struct OpenSSHKeyWriter {
/// Initializes the writer.
public init() {

View File

@ -2,7 +2,7 @@ import Foundation
import OSLog
/// Controller responsible for writing public keys to disk, so that they're easily accessible by scripts.
public final class PublicKeyFileStoreController: Sendable {
public final class PublicKeyFileStoreController {
private let logger = Logger(subsystem: "com.maxgoedjen.secretive.secretagent", category: "PublicKeyFileStoreController")
private let directory: String

View File

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

View File

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

View File

@ -1,7 +1,7 @@
import Foundation
/// The base protocol for describing a Secret
public protocol Secret: Identifiable, Hashable, Sendable {
public protocol Secret: Identifiable, Hashable {
/// A user-facing string identifying the Secret.
var name: String { get }
@ -17,7 +17,7 @@ public protocol Secret: Identifiable, Hashable, Sendable {
}
/// The type of algorithm the Secret uses. Currently, only elliptic curve algorithms are supported.
public enum Algorithm: Hashable, Sendable {
public enum Algorithm: Hashable {
case ellipticCurve
case rsa

View File

@ -2,7 +2,7 @@ import Foundation
import Combine
/// Manages access to Secrets, and performs signature operations on data using those Secrets.
public protocol SecretStore: Identifiable, Sendable {
public protocol SecretStore: ObservableObject, Identifiable {
associatedtype SecretType: Secret
@ -21,7 +21,7 @@ public protocol SecretStore: Identifiable, Sendable {
/// - secret: The ``Secret`` to sign with.
/// - provenance: A ``SigningRequestProvenance`` describing where the request came from.
/// - Returns: The signed data.
func sign(data: Data, with secret: SecretType, for provenance: SigningRequestProvenance) async throws -> Data
func sign(data: Data, with secret: SecretType, for provenance: SigningRequestProvenance) throws -> Data
/// Verifies that a signature is valid over a specified payload.
/// - Parameters:
@ -29,23 +29,23 @@ public protocol SecretStore: Identifiable, Sendable {
/// - data: The data to verify the signature of.
/// - secret: The secret whose signature to verify.
/// - Returns: Whether the signature was verified.
func verify(signature: Data, for data: Data, with secret: SecretType) async throws -> Bool
func verify(signature: Data, for data: Data, with secret: SecretType) throws -> Bool
/// Checks to see if there is currently a valid persisted authentication for a given secret.
/// - Parameters:
/// - secret: The ``Secret`` to check if there is a persisted authentication for.
/// - Returns: A persisted authentication context, if a valid one exists.
func existingPersistedAuthenticationContext(secret: SecretType) async -> PersistedAuthenticationContext?
func existingPersistedAuthenticationContext(secret: SecretType) -> PersistedAuthenticationContext?
/// Persists user authorization for access to a secret.
/// - Parameters:
/// - secret: The ``Secret`` to persist the authorization for.
/// - duration: The duration that the authorization should persist for.
/// - Note: This is used for temporarily unlocking access to a secret which would otherwise require authentication every single use. This is useful for situations where the user anticipates several rapid accesses to a authorization-guarded secret.
func persistAuthentication(secret: SecretType, forDuration duration: TimeInterval) async throws
func persistAuthentication(secret: SecretType, forDuration duration: TimeInterval) throws
/// Requests that the store reload secrets from any backing store, if neccessary.
func reloadSecrets() async
func reloadSecrets()
}
@ -56,18 +56,18 @@ public protocol SecretStoreModifiable: SecretStore {
/// - Parameters:
/// - name: The user-facing name for the ``Secret``.
/// - requiresAuthentication: A boolean indicating whether or not the user will be required to authenticate before performing signature operations with the secret.
func create(name: String, requiresAuthentication: Bool) async throws
func create(name: String, requiresAuthentication: Bool) throws
/// Deletes a Secret in the store.
/// - Parameters:
/// - secret: The ``Secret`` to delete.
func delete(secret: SecretType) async throws
func delete(secret: SecretType) throws
/// Updates the name of a Secret in the store.
/// - Parameters:
/// - secret: The ``Secret`` to update.
/// - name: The new name for the Secret.
func update(secret: SecretType, name: String) async throws
func update(secret: SecretType, name: String) throws
}

View File

@ -1,41 +1,38 @@
import Foundation
import Observation
import Combine
import Security
import CryptoKit
import CryptoTokenKit
import LocalAuthentication
import SecretKit
import Synchronization
extension SecureEnclave {
/// An implementation of Store backed by the Secure Enclave.
@Observable public final class Store: SecretStoreModifiable {
public final class Store: SecretStoreModifiable {
public var isAvailable: Bool {
CryptoKit.SecureEnclave.isAvailable
// For some reason, as of build time, CryptoKit.SecureEnclave.isAvailable always returns false
// error msg "Received error sending GET UNIQUE DEVICE command"
// Verify it with TKTokenWatcher manually.
TKTokenWatcher().tokenIDs.contains("com.apple.setoken")
}
public let id = UUID()
public let name = String(localized: "secure_enclave")
public var secrets: [Secret] {
_secrets.withLock { $0 }
}
private let _secrets: Mutex<[Secret]> = .init([])
@Published public private(set) var secrets: [Secret] = []
private let persistedAuthenticationContexts: Mutex<[Secret: PersistentAuthenticationContext]> = .init([:])
private var persistedAuthenticationContexts: [Secret: PersistentAuthenticationContext] = [:]
/// Initializes a Store.
public init() {
Task {
for await _ in DistributedNotificationCenter.default().notifications(named: .secretStoreUpdated) {
await reloadSecretsInternal(notifyAgent: false)
}
DistributedNotificationCenter.default().addObserver(forName: .secretStoreUpdated, object: nil, queue: .main) { [reload = reloadSecretsInternal(notifyAgent:)] _ in
reload(false)
}
loadSecrets()
}
// MARK: Public API
public func create(name: String, requiresAuthentication: Bool) async throws {
public func create(name: String, requiresAuthentication: Bool) throws {
var accessError: SecurityError?
let flags: SecAccessControlCreateFlags
if requiresAuthentication {
@ -72,10 +69,10 @@ extension SecureEnclave {
throw KeychainError(statusCode: nil)
}
try savePublicKey(publicKey, name: name)
await reloadSecretsInternal()
reloadSecretsInternal()
}
public func delete(secret: Secret) async throws {
public func delete(secret: Secret) throws {
let deleteAttributes = KeychainDictionary([
kSecClass: kSecClassKey,
kSecAttrApplicationLabel: secret.id as CFData
@ -84,10 +81,10 @@ extension SecureEnclave {
if status != errSecSuccess {
throw KeychainError(statusCode: status)
}
await reloadSecretsInternal()
reloadSecretsInternal()
}
public func update(secret: Secret, name: String) async throws {
public func update(secret: Secret, name: String) throws {
let updateQuery = KeychainDictionary([
kSecClass: kSecClassKey,
kSecAttrApplicationLabel: secret.id as CFData
@ -101,46 +98,44 @@ extension SecureEnclave {
if status != errSecSuccess {
throw KeychainError(statusCode: status)
}
await reloadSecretsInternal()
reloadSecretsInternal()
}
public func sign(data: Data, with secret: Secret, for provenance: SigningRequestProvenance) throws -> Data {
let context: Mutex<LAContext>
// if let existing = persistedAuthenticationContexts.withLock({ $0 })[secret], existing.valid {
// context = existing.context
// } else {
let context: LAContext
if let existing = persistedAuthenticationContexts[secret], existing.valid {
context = existing.context
} else {
let newContext = LAContext()
newContext.localizedCancelTitle = String(localized: "auth_context_request_deny_button")
context = .init(newContext)
// }
return try context.withLock { context in
context.localizedReason = String(localized: "auth_context_request_signature_description_\(provenance.origin.displayName)_\(secret.name)")
let attributes = KeychainDictionary([
kSecClass: kSecClassKey,
kSecAttrKeyClass: kSecAttrKeyClassPrivate,
kSecAttrApplicationLabel: secret.id as CFData,
kSecAttrKeyType: Constants.keyType,
kSecAttrTokenID: kSecAttrTokenIDSecureEnclave,
kSecAttrApplicationTag: Constants.keyTag,
kSecUseAuthenticationContext: context,
kSecReturnRef: true
])
var untyped: CFTypeRef?
let status = SecItemCopyMatching(attributes, &untyped)
if status != errSecSuccess {
throw KeychainError(statusCode: status)
}
guard let untypedSafe = untyped else {
throw KeychainError(statusCode: errSecSuccess)
}
let key = untypedSafe as! SecKey
var signError: SecurityError?
guard let signature = SecKeyCreateSignature(key, .ecdsaSignatureMessageX962SHA256, data as CFData, &signError) else {
throw SigningError(error: signError)
}
return signature as Data
context = newContext
}
context.localizedReason = String(localized: "auth_context_request_signature_description_\(provenance.origin.displayName)_\(secret.name)")
let attributes = KeychainDictionary([
kSecClass: kSecClassKey,
kSecAttrKeyClass: kSecAttrKeyClassPrivate,
kSecAttrApplicationLabel: secret.id as CFData,
kSecAttrKeyType: Constants.keyType,
kSecAttrTokenID: kSecAttrTokenIDSecureEnclave,
kSecAttrApplicationTag: Constants.keyTag,
kSecUseAuthenticationContext: context,
kSecReturnRef: true
])
var untyped: CFTypeRef?
let status = SecItemCopyMatching(attributes, &untyped)
if status != errSecSuccess {
throw KeychainError(statusCode: status)
}
guard let untypedSafe = untyped else {
throw KeychainError(statusCode: errSecSuccess)
}
let key = untypedSafe as! SecKey
var signError: SecurityError?
guard let signature = SecKeyCreateSignature(key, .ecdsaSignatureMessageX962SHA256, data as CFData, &signError) else {
throw SigningError(error: signError)
}
return signature as Data
}
public func verify(signature: Data, for data: Data, with secret: Secret) throws -> Bool {
@ -179,7 +174,7 @@ extension SecureEnclave {
}
public func existingPersistedAuthenticationContext(secret: Secret) -> PersistedAuthenticationContext? {
guard let persisted = persistedAuthenticationContexts.withLock({ $0 })[secret], persisted.valid else { return nil }
guard let persisted = persistedAuthenticationContexts[secret], persisted.valid else { return nil }
return persisted
}
@ -198,16 +193,14 @@ extension SecureEnclave {
newContext.localizedReason = String(localized: "auth_context_persist_for_duration_unknown_\(secret.name)")
}
newContext.evaluatePolicy(LAPolicy.deviceOwnerAuthentication, localizedReason: newContext.localizedReason) { [weak self] success, _ in
guard success, let self else { return }
guard success else { return }
let context = PersistentAuthenticationContext(secret: secret, context: newContext, duration: duration)
self.persistedAuthenticationContexts.withLock {
$0[secret] = context
}
self?.persistedAuthenticationContexts[secret] = context
}
}
public func reloadSecrets() async {
await reloadSecretsInternal(notifyAgent: false)
public func reloadSecrets() {
reloadSecretsInternal(notifyAgent: false)
}
}
@ -218,11 +211,9 @@ extension SecureEnclave.Store {
/// Reloads all secrets from the store.
/// - Parameter notifyAgent: A boolean indicating whether a distributed notification should be posted, notifying other processes (ie, the SecretAgent) to reload their stores as well.
private func reloadSecretsInternal(notifyAgent: Bool = true) async {
private func reloadSecretsInternal(notifyAgent: Bool = true) {
let before = secrets
_secrets.withLock {
$0.removeAll()
}
secrets.removeAll()
loadSecrets()
if secrets != before {
NotificationCenter.default.post(name: .secretStoreReloaded, object: self)
@ -284,9 +275,7 @@ extension SecureEnclave.Store {
}
return SecureEnclave.Secret(id: id, name: name, requiresAuthentication: requiresAuth, publicKey: publicKey)
}
_secrets.withLock {
$0.append(contentsOf: wrapped)
}
secrets.append(contentsOf: wrapped)
}
/// Saves a public key.
@ -315,8 +304,8 @@ extension SecureEnclave.Store {
extension SecureEnclave {
enum Constants {
static let keyTag = Data("com.maxgoedjen.secretive.secureenclave.key".utf8)
static let keyType = kSecAttrKeyTypeECSECPrimeRandom as String
static let keyTag = "com.maxgoedjen.secretive.secureenclave.key".data(using: .utf8)! as CFData
static let keyType = kSecAttrKeyTypeECSECPrimeRandom
static let unauthenticatedThreshold: TimeInterval = 0.05
}
@ -325,12 +314,12 @@ extension SecureEnclave {
extension SecureEnclave {
/// A context describing a persisted authentication.
private final class PersistentAuthenticationContext: PersistedAuthenticationContext {
private struct PersistentAuthenticationContext: PersistedAuthenticationContext {
/// The Secret to persist authentication for.
let secret: Secret
/// The LAContext used to authorize the persistent context.
nonisolated(unsafe) let context: LAContext
let context: LAContext
/// An expiration date for the context.
/// - Note - Monotonic time instead of Date() to prevent people setting the clock back.
let monotonicExpiration: UInt64

View File

@ -1,51 +1,38 @@
import Foundation
import Synchronization
import Observation
import Combine
import Security
import CryptoTokenKit
import LocalAuthentication
import SecretKit
extension SmartCard {
private struct State {
var isAvailable = false
var name = String(localized: "smart_card")
var secrets: [Secret] = []
let watcher = TKTokenWatcher()
var tokenID: String? = nil
}
/// An implementation of Store backed by a Smart Card.
@Observable public final class Store: SecretStore {
private let state: Mutex<State> = .init(.init())
public var isAvailable: Bool {
state.withLock { $0.isAvailable }
}
public final class Store: SecretStore {
@Published public var isAvailable: Bool = false
public let id = UUID()
public var name: String {
state.withLock { $0.name }
}
public var secrets: [Secret] {
state.withLock { $0.secrets }
}
public private(set) var name = String(localized: "smart_card")
@Published public private(set) var secrets: [Secret] = []
private let watcher = TKTokenWatcher()
private var tokenID: String?
/// Initializes a Store.
public init() {
state.withLock { state in
if let tokenID = state.tokenID {
state.isAvailable = true
state.watcher.addRemovalHandler(self.smartcardRemoved, forTokenID: tokenID)
}
state.watcher.setInsertionHandler { id in
// Setting insertion handler will cause it to be called immediately.
// Make a thread jump so we don't hit a recursive lock attempt.
Task {
self.smartcardInserted(for: id)
}
tokenID = watcher.nonSecureEnclaveTokens.first
watcher.setInsertionHandler { [reload = reloadSecretsInternal] string in
guard self.tokenID == nil else { return }
guard !string.contains("setoken") else { return }
self.tokenID = string
DispatchQueue.main.async {
reload()
}
self.watcher.addRemovalHandler(self.smartcardRemoved, forTokenID: string)
}
if let tokenID = tokenID {
self.isAvailable = true
self.watcher.addRemovalHandler(self.smartcardRemoved, forTokenID: tokenID)
}
loadSecrets()
}
@ -61,7 +48,7 @@ extension SmartCard {
}
public func sign(data: Data, with secret: Secret, for provenance: SigningRequestProvenance) throws -> Data {
guard let tokenID = state.withLock({ $0.tokenID }) else { fatalError() }
guard let tokenID = tokenID else { fatalError() }
let context = LAContext()
context.localizedReason = String(localized: "auth_context_request_signature_description_\(provenance.origin.displayName)_\(secret.name)")
context.localizedCancelTitle = String(localized: "auth_context_request_deny_button")
@ -131,51 +118,31 @@ extension SmartCard {
extension SmartCard.Store {
private func reloadSecretsInternal() {
let before = state.withLock {
$0.isAvailable = $0.tokenID != nil
let before = $0.secrets
$0.secrets.removeAll()
return before
}
self.isAvailable = self.tokenID != nil
let before = self.secrets
self.secrets.removeAll()
self.loadSecrets()
if self.secrets != before {
NotificationCenter.default.post(name: .secretStoreReloaded, object: self)
}
}
/// Resets the token ID and reloads secrets.
/// - Parameter tokenID: The ID of the token that was inserted.
private func smartcardInserted(for tokenID: String? = nil) {
state.withLock { state in
guard let string = state.watcher.nonSecureEnclaveTokens.first else { return }
guard state.tokenID == nil else { return }
guard !string.contains("setoken") else { return }
state.tokenID = string
state.watcher.addRemovalHandler(self.smartcardRemoved, forTokenID: string)
state.tokenID = string
}
}
/// Resets the token ID and reloads secrets.
/// - Parameter tokenID: The ID of the token that was removed.
private func smartcardRemoved(for tokenID: String? = nil) {
state.withLock {
$0.tokenID = nil
}
self.tokenID = nil
reloadSecrets()
}
/// Loads all secrets from the store.
private func loadSecrets() {
guard let tokenID = state.withLock({ $0.tokenID }) else { return }
guard let tokenID = tokenID else { return }
let fallbackName = String(localized: "smart_card")
state.withLock {
if let driverName = $0.watcher.tokenInfo(forTokenID: tokenID)?.driverName {
$0.name = driverName
} else {
$0.name = fallbackName
}
if let driverName = watcher.tokenInfo(forTokenID: tokenID)?.driverName {
name = driverName
} else {
name = fallbackName
}
let attributes = KeychainDictionary([
@ -199,9 +166,7 @@ extension SmartCard.Store {
let publicKey = publicKeyAttributes[kSecValueData] as! Data
return SmartCard.Secret(id: tokenID, name: name, algorithm: algorithm, keySize: keySize, publicKey: publicKey)
}
state.withLock {
$0.secrets.append(contentsOf: wrapped)
}
secrets.append(contentsOf: wrapped)
}
}
@ -245,7 +210,7 @@ extension SmartCard.Store {
/// - Returns: The decrypted data.
/// - Warning: Encryption functions are deliberately only exposed on a library level, and are not exposed in Secretive itself to prevent users from data loss. Any pull requests which expose this functionality in the app will not be merged.
public func decrypt(data: Data, with secret: SecretType) throws -> Data {
guard let tokenID = state.withLock({ $0.tokenID }) else { fatalError() }
guard let tokenID = tokenID else { fatalError() }
let context = LAContext()
context.localizedReason = String(localized: "auth_context_request_decrypt_description_\(secret.name)")
context.localizedCancelTitle = String(localized: "auth_context_request_deny_button")

View File

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

View File

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

View File

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

View File

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

View File

@ -6,7 +6,7 @@ struct Stub {}
extension Stub {
public final class Store: SecretStore, @unchecked Sendable {
public final class Store: SecretStore {
public let isAvailable = true
public let id = UUID()

View File

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

View File

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

View File

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

View File

@ -6,9 +6,8 @@ import SecureEnclaveSecretKit
import SmartCardSecretKit
import SecretAgentKit
import Brief
import Observation
@main
@NSApplicationMain
class AppDelegate: NSObject, NSApplicationDelegate {
private let storeList: SecretStoreList = {
@ -32,28 +31,19 @@ class AppDelegate: NSObject, NSApplicationDelegate {
func applicationDidFinishLaunching(_ aNotification: Notification) {
logger.debug("SecretAgent finished launching")
Task { @MainActor in
socketController.handler = { [agent] reader, writer in
await agent.handle(reader: reader, writer: writer)
}
DispatchQueue.main.async {
self.socketController.handler = self.agent.handle(reader:writer:)
}
Task {
for await _ in NotificationCenter.default.notifications(named: .secretStoreReloaded) {
try? publicKeyFileStoreController.generatePublicKeys(for: storeList.allSecrets, 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.allSecrets, clear: true)
notifier.prompt()
_ = withObservationTracking {
updater.update
} onChange: { [updater, notifier] in
notifier.notify(update: updater.update!) { release in
Task {
await updater.ignore(release: release)
}
}
updateSink = updater.$update.sink { update in
guard let update = update else { return }
self.notifier.notify(update: update, ignore: self.updater.ignore(release:))
}
}
}

View File

@ -4,9 +4,8 @@ import AppKit
import SecretKit
import SecretAgentKit
import Brief
import Synchronization
final class Notifier: Sendable {
class Notifier {
private let notificationDelegate = NotificationDelegate()
@ -35,9 +34,7 @@ final class Notifier: Sendable {
guard let string = formatter.string(from: seconds)?.capitalized else { continue }
let identifier = Constants.persistAuthenticationCategoryIdentitifier.appending("\(seconds)")
let action = UNNotificationAction(identifier: identifier, title: string, options: [])
notificationDelegate.state.withLock { state in
state.persistOptions[identifier] = seconds
}
notificationDelegate.persistOptions[identifier] = seconds
allPersistenceActions.append(action)
}
@ -48,11 +45,9 @@ final class Notifier: Sendable {
UNUserNotificationCenter.current().setNotificationCategories([updateCategory, criticalUpdateCategory, persistAuthenticationCategory])
UNUserNotificationCenter.current().delegate = notificationDelegate
notificationDelegate.state.withLock { state in
state.persistAuthentication = { secret, store, duration in
guard let duration = duration else { return }
try? await store.persistAuthentication(secret: secret, forDuration: duration)
}
notificationDelegate.persistAuthentication = { secret, store, duration in
guard let duration = duration else { return }
try? store.persistAuthentication(secret: secret, forDuration: duration)
}
}
@ -62,11 +57,9 @@ final class Notifier: Sendable {
notificationCenter.requestAuthorization(options: .alert) { _, _ in }
}
func notify(accessTo secret: AnySecret, from store: AnySecretStore, by provenance: SigningRequestProvenance) async {
notificationDelegate.state.withLock { state in
state.pendingPersistableSecrets[secret.id.description] = secret
state.pendingPersistableStores[store.id.description] = store
}
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()
let notificationContent = UNMutableNotificationContent()
notificationContent.title = String(localized: "signed_notification_title_\(provenance.origin.displayName)")
@ -74,21 +67,19 @@ final class Notifier: Sendable {
notificationContent.userInfo[Constants.persistSecretIDKey] = secret.id.description
notificationContent.userInfo[Constants.persistStoreIDKey] = store.id.description
notificationContent.interruptionLevel = .timeSensitive
if await store.existingPersistedAuthenticationContext(secret: secret) == nil && secret.requiresAuthentication {
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) {
notificationContent.attachments = [attachment]
}
let request = UNNotificationRequest(identifier: UUID().uuidString, content: notificationContent, trigger: nil)
try? await notificationCenter.add(request)
notificationCenter.add(request, withCompletionHandler: nil)
}
func notify(update: Release, ignore: ((Release) -> Void)?) {
notificationDelegate.state.withLock { [update] state in
state.release = update
// state.ignore = ignore
}
notificationDelegate.release = update
notificationDelegate.ignore = ignore
let notificationCenter = UNUserNotificationCenter.current()
let notificationContent = UNMutableNotificationContent()
if update.critical {
@ -108,11 +99,11 @@ final class Notifier: Sendable {
extension Notifier: SigningWitness {
func speakNowOrForeverHoldYourPeace(forAccessTo secret: AnySecret, from store: AnySecretStore, by provenance: SigningRequestProvenance) async throws {
func speakNowOrForeverHoldYourPeace(forAccessTo secret: AnySecret, from store: AnySecretStore, by provenance: SigningRequestProvenance) throws {
}
func witness(accessTo secret: AnySecret, from store: AnySecretStore, by provenance: SigningRequestProvenance) async throws {
await notify(accessTo: secret, from: store, by: provenance)
func witness(accessTo secret: AnySecret, from store: AnySecretStore, by provenance: SigningRequestProvenance) throws {
notify(accessTo: secret, from: store, by: provenance)
}
}
@ -138,66 +129,55 @@ extension Notifier {
}
final class NotificationDelegate: NSObject, UNUserNotificationCenterDelegate, Sendable {
class NotificationDelegate: NSObject, UNUserNotificationCenterDelegate {
fileprivate var release: Release?
fileprivate var ignore: ((Release) -> Void)?
fileprivate var persistAuthentication: ((AnySecret, AnySecretStore, TimeInterval?) -> Void)?
fileprivate var persistOptions: [String: TimeInterval] = [:]
fileprivate var pendingPersistableStores: [String: AnySecretStore] = [:]
fileprivate var pendingPersistableSecrets: [String: AnySecret] = [:]
struct State {
typealias PersistAuthentication = ((AnySecret, AnySecretStore, TimeInterval?) async -> Void)
typealias Ignore = ((Release) -> Void)
fileprivate var release: Release?
fileprivate var ignore: Ignore?
fileprivate var persistAuthentication: PersistAuthentication?
fileprivate var persistOptions: [String: TimeInterval] = [:]
fileprivate var pendingPersistableStores: [String: AnySecretStore] = [:]
fileprivate var pendingPersistableSecrets: [String: AnySecret] = [:]
}
fileprivate let state: Mutex<State> = .init(.init())
func userNotificationCenter(_ center: UNUserNotificationCenter, openSettingsFor notification: UNNotification?) {
}
func userNotificationCenter(_ center: UNUserNotificationCenter, didReceive response: UNNotificationResponse) async {
func userNotificationCenter(_ center: UNUserNotificationCenter, didReceive response: UNNotificationResponse, withCompletionHandler completionHandler: @escaping () -> Void) {
let category = response.notification.request.content.categoryIdentifier
switch category {
case Notifier.Constants.updateCategoryIdentitifier:
handleUpdateResponse(response: response)
case Notifier.Constants.persistAuthenticationCategoryIdentitifier:
await handlePersistAuthenticationResponse(response: response)
handlePersistAuthenticationResponse(response: response)
default:
break
}
completionHandler()
}
func handleUpdateResponse(response: UNNotificationResponse) {
state.withLock { state in
guard let update = state.release else { return }
switch response.actionIdentifier {
case Notifier.Constants.updateActionIdentitifier, UNNotificationDefaultActionIdentifier:
NSWorkspace.shared.open(update.html_url)
case Notifier.Constants.ignoreActionIdentitifier:
state.ignore?(update)
default:
fatalError()
}
guard let update = release else { return }
switch response.actionIdentifier {
case Notifier.Constants.updateActionIdentitifier, UNNotificationDefaultActionIdentifier:
NSWorkspace.shared.open(update.html_url)
case Notifier.Constants.ignoreActionIdentitifier:
ignore?(update)
default:
fatalError()
}
}
func handlePersistAuthenticationResponse(response: UNNotificationResponse) async {
// let (secret, store, persistOptions, callback): (AnySecret?, AnySecretStore?, TimeInterval?, State.PersistAuthentication?) = state.withLock { state in
// guard let secretID = response.notification.request.content.userInfo[Notifier.Constants.persistSecretIDKey] as? String, let secret = state.pendingPersistableSecrets[secretID],
// let storeID = response.notification.request.content.userInfo[Notifier.Constants.persistStoreIDKey] as? String, let store = state.pendingPersistableStores[storeID]
// else { return (nil, nil, nil, nil) }
// state.pendingPersistableSecrets[secretID] = nil
// return (secret, store, state.persistOptions[response.actionIdentifier], state.persistAuthentication)
// }
// guard let secret, let store, let persistOptions else { return }
// await callback?(secret, store, persistOptions)
func handlePersistAuthenticationResponse(response: UNNotificationResponse) {
guard let secretID = response.notification.request.content.userInfo[Notifier.Constants.persistSecretIDKey] as? String, let secret = pendingPersistableSecrets[secretID],
let storeID = response.notification.request.content.userInfo[Notifier.Constants.persistStoreIDKey] as? String, let store = pendingPersistableStores[storeID]
else { return }
pendingPersistableSecrets[secretID] = nil
persistAuthentication?(secret, store, persistOptions[response.actionIdentifier])
}
func userNotificationCenter(_ center: UNUserNotificationCenter, willPresent notification: UNNotification) async -> UNNotificationPresentationOptions {
[.list, .banner]
func userNotificationCenter(_ center: UNUserNotificationCenter, willPresent notification: UNNotification, withCompletionHandler completionHandler: @escaping (UNNotificationPresentationOptions) -> Void) {
completionHandler([.list, .banner])
}
}

View File

@ -4,6 +4,16 @@
<dict>
<key>com.apple.security.app-sandbox</key>
<true/>
<key>com.apple.security.hardened-process</key>
<true/>
<key>com.apple.security.hardened-process.dyld-ro</key>
<true/>
<key>com.apple.security.hardened-process.enhanced-security-version</key>
<integer>1</integer>
<key>com.apple.security.hardened-process.hardened-heap</key>
<true/>
<key>com.apple.security.hardened-process.platform-restrictions</key>
<integer>2</integer>
<key>com.apple.security.network.client</key>
<true/>
<key>com.apple.security.smartcard</key>

View File

@ -3,7 +3,7 @@
archiveVersion = 1;
classes = {
};
objectVersion = 54;
objectVersion = 60;
objects = {
/* Begin PBXBuildFile section */
@ -30,6 +30,7 @@
50617D8523FCE48E0099B055 /* ContentView.swift in Sources */ = {isa = PBXBuildFile; fileRef = 50617D8423FCE48E0099B055 /* ContentView.swift */; };
50617D8723FCE48E0099B055 /* Assets.xcassets in Resources */ = {isa = PBXBuildFile; fileRef = 50617D8623FCE48E0099B055 /* Assets.xcassets */; };
50617D8A23FCE48E0099B055 /* Preview Assets.xcassets in Resources */ = {isa = PBXBuildFile; fileRef = 50617D8923FCE48E0099B055 /* Preview Assets.xcassets */; };
50617D9923FCE48E0099B055 /* SecretiveTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 50617D9823FCE48E0099B055 /* SecretiveTests.swift */; };
50617DD223FCEFA90099B055 /* PreviewStore.swift in Sources */ = {isa = PBXBuildFile; fileRef = 50617DD123FCEFA90099B055 /* PreviewStore.swift */; };
5065E313295517C500E16645 /* ToolbarButtonStyle.swift in Sources */ = {isa = PBXBuildFile; fileRef = 5065E312295517C500E16645 /* ToolbarButtonStyle.swift */; };
5066A6C22516F303004B5A36 /* SetupView.swift in Sources */ = {isa = PBXBuildFile; fileRef = 5066A6C12516F303004B5A36 /* SetupView.swift */; };
@ -62,6 +63,13 @@
remoteGlobalIDString = 50A3B78924026B7500D209EA;
remoteInfo = SecretAgent;
};
50617D9523FCE48E0099B055 /* PBXContainerItemProxy */ = {
isa = PBXContainerItemProxy;
containerPortal = 50617D7723FCE48D0099B055 /* Project object */;
proxyType = 1;
remoteGlobalIDString = 50617D7E23FCE48D0099B055;
remoteInfo = Secretive;
};
/* End PBXContainerItemProxy section */
/* Begin PBXCopyFilesBuildPhase section */
@ -115,6 +123,9 @@
50617D8923FCE48E0099B055 /* Preview Assets.xcassets */ = {isa = PBXFileReference; lastKnownFileType = folder.assetcatalog; path = "Preview Assets.xcassets"; sourceTree = "<group>"; };
50617D8E23FCE48E0099B055 /* Info.plist */ = {isa = PBXFileReference; lastKnownFileType = text.plist.xml; path = Info.plist; sourceTree = "<group>"; };
50617D8F23FCE48E0099B055 /* Secretive.entitlements */ = {isa = PBXFileReference; lastKnownFileType = text.plist.entitlements; path = Secretive.entitlements; sourceTree = "<group>"; };
50617D9423FCE48E0099B055 /* SecretiveTests.xctest */ = {isa = PBXFileReference; explicitFileType = wrapper.cfbundle; includeInIndex = 0; path = SecretiveTests.xctest; sourceTree = BUILT_PRODUCTS_DIR; };
50617D9823FCE48E0099B055 /* SecretiveTests.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = SecretiveTests.swift; sourceTree = "<group>"; };
50617D9A23FCE48E0099B055 /* Info.plist */ = {isa = PBXFileReference; lastKnownFileType = text.plist.xml; path = Info.plist; sourceTree = "<group>"; };
50617DD123FCEFA90099B055 /* PreviewStore.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = PreviewStore.swift; sourceTree = "<group>"; };
5065E312295517C500E16645 /* ToolbarButtonStyle.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = ToolbarButtonStyle.swift; sourceTree = "<group>"; };
5066A6C12516F303004B5A36 /* SetupView.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = SetupView.swift; sourceTree = "<group>"; };
@ -155,6 +166,13 @@
);
runOnlyForDeploymentPostprocessing = 0;
};
50617D9123FCE48E0099B055 /* Frameworks */ = {
isa = PBXFrameworksBuildPhase;
buildActionMask = 2147483647;
files = (
);
runOnlyForDeploymentPostprocessing = 0;
};
50A3B78724026B7500D209EA /* Frameworks */ = {
isa = PBXFrameworksBuildPhase;
buildActionMask = 2147483647;
@ -183,6 +201,7 @@
children = (
5003EF39278005C800DF2006 /* Packages */,
50617D8123FCE48E0099B055 /* Secretive */,
50617D9723FCE48E0099B055 /* SecretiveTests */,
50A3B78B24026B7500D209EA /* SecretAgent */,
508A58AF241E144C0069DC07 /* Config */,
50617D8023FCE48E0099B055 /* Products */,
@ -194,6 +213,7 @@
isa = PBXGroup;
children = (
50617D7F23FCE48E0099B055 /* Secretive.app */,
50617D9423FCE48E0099B055 /* SecretiveTests.xctest */,
50A3B78A24026B7500D209EA /* SecretAgent.app */,
);
name = Products;
@ -228,6 +248,15 @@
path = "Preview Content";
sourceTree = "<group>";
};
50617D9723FCE48E0099B055 /* SecretiveTests */ = {
isa = PBXGroup;
children = (
50617D9823FCE48E0099B055 /* SecretiveTests.swift */,
50617D9A23FCE48E0099B055 /* Info.plist */,
);
path = SecretiveTests;
sourceTree = "<group>";
};
508A58AF241E144C0069DC07 /* Config */ = {
isa = PBXGroup;
children = (
@ -328,6 +357,24 @@
productReference = 50617D7F23FCE48E0099B055 /* Secretive.app */;
productType = "com.apple.product-type.application";
};
50617D9323FCE48E0099B055 /* SecretiveTests */ = {
isa = PBXNativeTarget;
buildConfigurationList = 50617DA023FCE48E0099B055 /* Build configuration list for PBXNativeTarget "SecretiveTests" */;
buildPhases = (
50617D9023FCE48E0099B055 /* Sources */,
50617D9123FCE48E0099B055 /* Frameworks */,
50617D9223FCE48E0099B055 /* Resources */,
);
buildRules = (
);
dependencies = (
50617D9623FCE48E0099B055 /* PBXTargetDependency */,
);
name = SecretiveTests;
productName = SecretiveTests;
productReference = 50617D9423FCE48E0099B055 /* SecretiveTests.xctest */;
productType = "com.apple.product-type.bundle.unit-test";
};
50A3B78924026B7500D209EA /* SecretAgent */ = {
isa = PBXNativeTarget;
buildConfigurationList = 50A3B79A24026B7600D209EA /* Build configuration list for PBXNativeTarget "SecretAgent" */;
@ -366,6 +413,10 @@
50617D7E23FCE48D0099B055 = {
CreatedOnToolsVersion = 11.3;
};
50617D9323FCE48E0099B055 = {
CreatedOnToolsVersion = 11.3;
TestTargetID = 50617D7E23FCE48D0099B055;
};
50A3B78924026B7500D209EA = {
CreatedOnToolsVersion = 11.4;
};
@ -387,11 +438,15 @@
ca,
);
mainGroup = 50617D7623FCE48D0099B055;
packageReferences = (
5068431C2DFE2DE000920856 /* XCLocalSwiftPackageReference "Packages" */,
);
productRefGroup = 50617D8023FCE48E0099B055 /* Products */;
projectDirPath = "";
projectRoot = "";
targets = (
50617D7E23FCE48D0099B055 /* Secretive */,
50617D9323FCE48E0099B055 /* SecretiveTests */,
50A3B78924026B7500D209EA /* SecretAgent */,
);
};
@ -410,6 +465,13 @@
);
runOnlyForDeploymentPostprocessing = 0;
};
50617D9223FCE48E0099B055 /* Resources */ = {
isa = PBXResourcesBuildPhase;
buildActionMask = 2147483647;
files = (
);
runOnlyForDeploymentPostprocessing = 0;
};
50A3B78824026B7500D209EA /* Resources */ = {
isa = PBXResourcesBuildPhase;
buildActionMask = 2147483647;
@ -455,6 +517,14 @@
);
runOnlyForDeploymentPostprocessing = 0;
};
50617D9023FCE48E0099B055 /* Sources */ = {
isa = PBXSourcesBuildPhase;
buildActionMask = 2147483647;
files = (
50617D9923FCE48E0099B055 /* SecretiveTests.swift in Sources */,
);
runOnlyForDeploymentPostprocessing = 0;
};
50A3B78624026B7500D209EA /* Sources */ = {
isa = PBXSourcesBuildPhase;
buildActionMask = 2147483647;
@ -472,6 +542,11 @@
target = 50A3B78924026B7500D209EA /* SecretAgent */;
targetProxy = 50142166278126B500BBAA70 /* PBXContainerItemProxy */;
};
50617D9623FCE48E0099B055 /* PBXTargetDependency */ = {
isa = PBXTargetDependency;
target = 50617D7E23FCE48D0099B055 /* Secretive */;
targetProxy = 50617D9523FCE48E0099B055 /* PBXContainerItemProxy */;
};
/* End PBXTargetDependency section */
/* Begin PBXVariantGroup section */
@ -522,6 +597,8 @@
CLANG_WARN__DUPLICATE_METHOD_MATCH = YES;
COPY_PHASE_STRIP = NO;
DEBUG_INFORMATION_FORMAT = dwarf;
ENABLE_ENHANCED_SECURITY = YES;
ENABLE_POINTER_AUTHENTICATION = YES;
ENABLE_STRICT_OBJC_MSGSEND = YES;
ENABLE_TESTABILITY = YES;
GCC_C_LANGUAGE_STANDARD = gnu11;
@ -538,7 +615,7 @@
GCC_WARN_UNINITIALIZED_AUTOS = YES_AGGRESSIVE;
GCC_WARN_UNUSED_FUNCTION = YES;
GCC_WARN_UNUSED_VARIABLE = YES;
MACOSX_DEPLOYMENT_TARGET = 15.0;
MACOSX_DEPLOYMENT_TARGET = 11.0;
MTL_ENABLE_DEBUG_INFO = INCLUDE_SOURCE;
MTL_FAST_MATH = YES;
ONLY_ACTIVE_ARCH = YES;
@ -549,7 +626,6 @@
SWIFT_ACTIVE_COMPILATION_CONDITIONS = DEBUG;
SWIFT_EMIT_LOC_STRINGS = YES;
SWIFT_OPTIMIZATION_LEVEL = "-Onone";
SWIFT_VERSION = 6.0;
};
name = Debug;
};
@ -589,7 +665,9 @@
CLANG_WARN__DUPLICATE_METHOD_MATCH = YES;
COPY_PHASE_STRIP = NO;
DEBUG_INFORMATION_FORMAT = "dwarf-with-dsym";
ENABLE_ENHANCED_SECURITY = YES;
ENABLE_NS_ASSERTIONS = NO;
ENABLE_POINTER_AUTHENTICATION = YES;
ENABLE_STRICT_OBJC_MSGSEND = YES;
GCC_C_LANGUAGE_STANDARD = gnu11;
GCC_NO_COMMON_BLOCKS = YES;
@ -599,7 +677,7 @@
GCC_WARN_UNINITIALIZED_AUTOS = YES_AGGRESSIVE;
GCC_WARN_UNUSED_FUNCTION = YES;
GCC_WARN_UNUSED_VARIABLE = YES;
MACOSX_DEPLOYMENT_TARGET = 15.0;
MACOSX_DEPLOYMENT_TARGET = 11.0;
MTL_ENABLE_DEBUG_INFO = NO;
MTL_FAST_MATH = YES;
OTHER_SWIFT_FLAGS = "";
@ -609,7 +687,6 @@
SWIFT_COMPILATION_MODE = wholemodule;
SWIFT_EMIT_LOC_STRINGS = YES;
SWIFT_OPTIMIZATION_LEVEL = "-O";
SWIFT_VERSION = 6.0;
};
name = Release;
};
@ -625,17 +702,21 @@
CURRENT_PROJECT_VERSION = 1;
DEVELOPMENT_ASSET_PATHS = "\"Secretive/Preview Content\"";
DEVELOPMENT_TEAM = Z72PRUAWF6;
ENABLE_ENHANCED_SECURITY = YES;
ENABLE_HARDENED_RUNTIME = YES;
ENABLE_POINTER_AUTHENTICATION = YES;
ENABLE_PREVIEWS = YES;
INFOPLIST_FILE = Secretive/Info.plist;
LD_RUNPATH_SEARCH_PATHS = (
"$(inherited)",
"@executable_path/../Frameworks",
);
MACOSX_DEPLOYMENT_TARGET = 13.0;
MARKETING_VERSION = 1;
PRODUCT_BUNDLE_IDENTIFIER = com.maxgoedjen.Secretive.Host;
PRODUCT_NAME = "$(TARGET_NAME)";
PROVISIONING_PROFILE_SPECIFIER = "";
SWIFT_VERSION = 5.0;
};
name = Debug;
};
@ -651,17 +732,63 @@
CURRENT_PROJECT_VERSION = 1;
DEVELOPMENT_ASSET_PATHS = "\"Secretive/Preview Content\"";
DEVELOPMENT_TEAM = Z72PRUAWF6;
ENABLE_ENHANCED_SECURITY = YES;
ENABLE_HARDENED_RUNTIME = YES;
ENABLE_POINTER_AUTHENTICATION = YES;
ENABLE_PREVIEWS = YES;
INFOPLIST_FILE = Secretive/Info.plist;
LD_RUNPATH_SEARCH_PATHS = (
"$(inherited)",
"@executable_path/../Frameworks",
);
MACOSX_DEPLOYMENT_TARGET = 13.0;
MARKETING_VERSION = 1;
PRODUCT_BUNDLE_IDENTIFIER = com.maxgoedjen.Secretive.Host;
PRODUCT_NAME = "$(TARGET_NAME)";
PROVISIONING_PROFILE_SPECIFIER = "Secretive - Host";
SWIFT_VERSION = 5.0;
};
name = Release;
};
50617DA123FCE48E0099B055 /* Debug */ = {
isa = XCBuildConfiguration;
buildSettings = {
ALWAYS_EMBED_SWIFT_STANDARD_LIBRARIES = YES;
BUNDLE_LOADER = "$(TEST_HOST)";
CODE_SIGN_STYLE = Automatic;
COMBINE_HIDPI_IMAGES = YES;
DEVELOPMENT_TEAM = Z72PRUAWF6;
INFOPLIST_FILE = SecretiveTests/Info.plist;
LD_RUNPATH_SEARCH_PATHS = (
"$(inherited)",
"@executable_path/../Frameworks",
"@loader_path/../Frameworks",
);
PRODUCT_BUNDLE_IDENTIFIER = com.maxgoedjen.SecretiveTests;
PRODUCT_NAME = "$(TARGET_NAME)";
SWIFT_VERSION = 5.0;
TEST_HOST = "$(BUILT_PRODUCTS_DIR)/Secretive.app/Contents/MacOS/Secretive";
};
name = Debug;
};
50617DA223FCE48E0099B055 /* Release */ = {
isa = XCBuildConfiguration;
buildSettings = {
ALWAYS_EMBED_SWIFT_STANDARD_LIBRARIES = YES;
BUNDLE_LOADER = "$(TEST_HOST)";
CODE_SIGN_STYLE = Automatic;
COMBINE_HIDPI_IMAGES = YES;
DEVELOPMENT_TEAM = Z72PRUAWF6;
INFOPLIST_FILE = SecretiveTests/Info.plist;
LD_RUNPATH_SEARCH_PATHS = (
"$(inherited)",
"@executable_path/../Frameworks",
"@loader_path/../Frameworks",
);
PRODUCT_BUNDLE_IDENTIFIER = com.maxgoedjen.SecretiveTests;
PRODUCT_NAME = "$(TARGET_NAME)";
SWIFT_VERSION = 5.0;
TEST_HOST = "$(BUILT_PRODUCTS_DIR)/Secretive.app/Contents/MacOS/Secretive";
};
name = Release;
};
@ -701,6 +828,8 @@
CLANG_WARN__DUPLICATE_METHOD_MATCH = YES;
COPY_PHASE_STRIP = NO;
DEBUG_INFORMATION_FORMAT = dwarf;
ENABLE_ENHANCED_SECURITY = YES;
ENABLE_POINTER_AUTHENTICATION = YES;
ENABLE_STRICT_OBJC_MSGSEND = YES;
ENABLE_TESTABILITY = YES;
GCC_C_LANGUAGE_STANDARD = gnu11;
@ -717,7 +846,7 @@
GCC_WARN_UNINITIALIZED_AUTOS = YES_AGGRESSIVE;
GCC_WARN_UNUSED_FUNCTION = YES;
GCC_WARN_UNUSED_VARIABLE = YES;
MACOSX_DEPLOYMENT_TARGET = 15.0;
MACOSX_DEPLOYMENT_TARGET = 11.0;
MTL_ENABLE_DEBUG_INFO = INCLUDE_SOURCE;
MTL_FAST_MATH = YES;
ONLY_ACTIVE_ARCH = YES;
@ -728,7 +857,6 @@
SWIFT_ACTIVE_COMPILATION_CONDITIONS = DEBUG;
SWIFT_EMIT_LOC_STRINGS = YES;
SWIFT_OPTIMIZATION_LEVEL = "-Onone";
SWIFT_VERSION = 6.0;
};
name = Test;
};
@ -737,20 +865,47 @@
buildSettings = {
ALWAYS_EMBED_SWIFT_STANDARD_LIBRARIES = YES;
ASSETCATALOG_COMPILER_APPICON_NAME = AppIcon;
CODE_SIGN_ENTITLEMENTS = Secretive/Secretive.entitlements;
CODE_SIGN_STYLE = Manual;
COMBINE_HIDPI_IMAGES = YES;
CURRENT_PROJECT_VERSION = 1;
DEVELOPMENT_ASSET_PATHS = "\"Secretive/Preview Content\"";
ENABLE_ENHANCED_SECURITY = YES;
ENABLE_HARDENED_RUNTIME = NO;
ENABLE_POINTER_AUTHENTICATION = YES;
ENABLE_PREVIEWS = YES;
INFOPLIST_FILE = Secretive/Info.plist;
LD_RUNPATH_SEARCH_PATHS = (
"$(inherited)",
"@executable_path/../Frameworks",
);
MACOSX_DEPLOYMENT_TARGET = 13.0;
MARKETING_VERSION = 1;
PRODUCT_BUNDLE_IDENTIFIER = com.maxgoedjen.Secretive.Host;
PRODUCT_NAME = "$(TARGET_NAME)";
SWIFT_VERSION = 5.0;
};
name = Test;
};
508A5916241EF1A00069DC07 /* Test */ = {
isa = XCBuildConfiguration;
buildSettings = {
ALWAYS_EMBED_SWIFT_STANDARD_LIBRARIES = YES;
BUNDLE_LOADER = "$(TEST_HOST)";
CODE_SIGN_IDENTITY = "-";
CODE_SIGN_STYLE = Manual;
COMBINE_HIDPI_IMAGES = YES;
INFOPLIST_FILE = SecretiveTests/Info.plist;
LD_RUNPATH_SEARCH_PATHS = (
"$(inherited)",
"@executable_path/../Frameworks",
"@loader_path/../Frameworks",
);
PRODUCT_BUNDLE_IDENTIFIER = com.maxgoedjen.SecretiveTests;
PRODUCT_NAME = "$(TARGET_NAME)";
PROVISIONING_PROFILE_SPECIFIER = "";
SWIFT_VERSION = 5.0;
TEST_HOST = "$(BUILT_PRODUCTS_DIR)/Secretive.app/Contents/MacOS/Secretive";
};
name = Test;
};
@ -758,19 +913,24 @@
isa = XCBuildConfiguration;
buildSettings = {
ASSETCATALOG_COMPILER_APPICON_NAME = AppIcon;
CODE_SIGN_ENTITLEMENTS = SecretAgent/SecretAgent.entitlements;
CODE_SIGN_STYLE = Manual;
COMBINE_HIDPI_IMAGES = YES;
DEVELOPMENT_ASSET_PATHS = "\"SecretAgent/Preview Content\"";
ENABLE_ENHANCED_SECURITY = YES;
ENABLE_HARDENED_RUNTIME = YES;
ENABLE_POINTER_AUTHENTICATION = YES;
ENABLE_PREVIEWS = YES;
INFOPLIST_FILE = SecretAgent/Info.plist;
LD_RUNPATH_SEARCH_PATHS = (
"$(inherited)",
"@executable_path/../Frameworks",
);
MACOSX_DEPLOYMENT_TARGET = 13.0;
MARKETING_VERSION = 1;
PRODUCT_BUNDLE_IDENTIFIER = com.maxgoedjen.Secretive.SecretAgent;
PRODUCT_NAME = "$(TARGET_NAME)";
SWIFT_VERSION = 5.0;
};
name = Test;
};
@ -783,16 +943,20 @@
COMBINE_HIDPI_IMAGES = YES;
DEVELOPMENT_ASSET_PATHS = "\"SecretAgent/Preview Content\"";
DEVELOPMENT_TEAM = Z72PRUAWF6;
ENABLE_ENHANCED_SECURITY = YES;
ENABLE_HARDENED_RUNTIME = YES;
ENABLE_POINTER_AUTHENTICATION = YES;
ENABLE_PREVIEWS = YES;
INFOPLIST_FILE = SecretAgent/Info.plist;
LD_RUNPATH_SEARCH_PATHS = (
"$(inherited)",
"@executable_path/../Frameworks",
);
MACOSX_DEPLOYMENT_TARGET = 13.0;
MARKETING_VERSION = 1;
PRODUCT_BUNDLE_IDENTIFIER = com.maxgoedjen.Secretive.SecretAgent;
PRODUCT_NAME = "$(TARGET_NAME)";
SWIFT_VERSION = 5.0;
};
name = Debug;
};
@ -806,17 +970,21 @@
COMBINE_HIDPI_IMAGES = YES;
DEVELOPMENT_ASSET_PATHS = "\"SecretAgent/Preview Content\"";
DEVELOPMENT_TEAM = Z72PRUAWF6;
ENABLE_ENHANCED_SECURITY = YES;
ENABLE_HARDENED_RUNTIME = YES;
ENABLE_POINTER_AUTHENTICATION = YES;
ENABLE_PREVIEWS = YES;
INFOPLIST_FILE = SecretAgent/Info.plist;
LD_RUNPATH_SEARCH_PATHS = (
"$(inherited)",
"@executable_path/../Frameworks",
);
MACOSX_DEPLOYMENT_TARGET = 13.0;
MARKETING_VERSION = 1;
PRODUCT_BUNDLE_IDENTIFIER = com.maxgoedjen.Secretive.SecretAgent;
PRODUCT_NAME = "$(TARGET_NAME)";
PROVISIONING_PROFILE_SPECIFIER = "Secretive - Secret Agent";
SWIFT_VERSION = 5.0;
};
name = Release;
};
@ -843,6 +1011,16 @@
defaultConfigurationIsVisible = 0;
defaultConfigurationName = Release;
};
50617DA023FCE48E0099B055 /* Build configuration list for PBXNativeTarget "SecretiveTests" */ = {
isa = XCConfigurationList;
buildConfigurations = (
50617DA123FCE48E0099B055 /* Debug */,
508A5916241EF1A00069DC07 /* Test */,
50617DA223FCE48E0099B055 /* Release */,
);
defaultConfigurationIsVisible = 0;
defaultConfigurationName = Release;
};
50A3B79A24026B7600D209EA /* Build configuration list for PBXNativeTarget "SecretAgent" */ = {
isa = XCConfigurationList;
buildConfigurations = (
@ -855,6 +1033,13 @@
};
/* End XCConfigurationList section */
/* Begin XCLocalSwiftPackageReference section */
5068431C2DFE2DE000920856 /* XCLocalSwiftPackageReference "Packages" */ = {
isa = XCLocalSwiftPackageReference;
relativePath = Packages;
};
/* End XCLocalSwiftPackageReference section */
/* Begin XCSwiftPackageProductDependency section */
5003EF3A278005E800DF2006 /* SecretKit */ = {
isa = XCSwiftPackageProductDependency;

View File

@ -5,20 +5,9 @@ import SecureEnclaveSecretKit
import SmartCardSecretKit
import Brief
extension EnvironmentValues {
@Entry var secretStoreList: SecretStoreList = {
let list = SecretStoreList()
list.add(store: SecureEnclave.Store())
list.add(store: SmartCard.Store())
return list
}()
@Entry var agentStatusChecker: any AgentStatusCheckerProtocol = AgentStatusChecker()
@Entry var updater: any UpdaterProtocol = Updater(checkOnLaunch: false)
}
@main
struct Secretive: App {
private let storeList: SecretStoreList = {
let list = SecretStoreList()
list.add(store: SecureEnclave.Store())
@ -34,10 +23,10 @@ struct Secretive: App {
@SceneBuilder var body: some Scene {
WindowGroup {
ContentView(showingCreation: $showingCreation, runningSetup: $showingSetup, hasRunSetup: $hasRunSetup)
.environment(storeList)
.environment(Updater(checkOnLaunch: hasRunSetup))
.environment(agentStatusChecker)
ContentView<Updater, AgentStatusChecker>(showingCreation: $showingCreation, runningSetup: $showingSetup, hasRunSetup: $hasRunSetup)
.environmentObject(storeList)
.environmentObject(Updater(checkOnLaunch: hasRunSetup))
.environmentObject(agentStatusChecker)
.onAppear {
if !hasRunSetup {
showingSetup = true
@ -81,12 +70,13 @@ extension Secretive {
private func reinstallAgent() {
justUpdatedChecker.check()
Task {
await LaunchAgentController().install()
try? await Task.sleep(for: .seconds(1))
agentStatusChecker.check()
if !agentStatusChecker.running {
forceLaunchAgent()
LaunchAgentController().install {
// Wait a second for launchd to kick in (next runloop isn't enough).
DispatchQueue.main.asyncAfter(deadline: .now() + 1) {
agentStatusChecker.check()
if !agentStatusChecker.running {
forceLaunchAgent()
}
}
}
}
@ -94,8 +84,7 @@ extension Secretive {
private func forceLaunchAgent() {
// We've run setup, we didn't just update, launchd is just not doing it's thing.
// Force a launch directly.
Task {
_ = await LaunchAgentController().forceLaunch()
LaunchAgentController().forceLaunch { _ in
agentStatusChecker.check()
}
}

View File

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

View File

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

View File

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

View File

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

View File

@ -6,6 +6,16 @@
<true/>
<key>com.apple.security.files.user-selected.read-write</key>
<true/>
<key>com.apple.security.hardened-process</key>
<true/>
<key>com.apple.security.hardened-process.dyld-ro</key>
<true/>
<key>com.apple.security.hardened-process.enhanced-security-version</key>
<integer>1</integer>
<key>com.apple.security.hardened-process.hardened-heap</key>
<true/>
<key>com.apple.security.hardened-process.platform-restrictions</key>
<integer>2</integer>
<key>com.apple.security.network.client</key>
<true/>
<key>com.apple.security.smartcard</key>

View File

@ -4,7 +4,7 @@ import SecureEnclaveSecretKit
import SmartCardSecretKit
import Brief
struct ContentView: View {
struct ContentView<UpdaterType: UpdaterProtocol, AgentStatusCheckerType: AgentStatusCheckerProtocol>: View {
@Binding var showingCreation: Bool
@Binding var runningSetup: Bool
@ -13,9 +13,9 @@ struct ContentView: View {
@State var activeSecret: AnySecret.ID?
@Environment(\.colorScheme) var colorScheme
@Environment(\.secretStoreList) private var storeList: SecretStoreList
@Environment(\.updater) private var updater: any UpdaterProtocol
@Environment(\.agentStatusChecker) private var agentStatusChecker: any AgentStatusCheckerProtocol
@EnvironmentObject private var storeList: SecretStoreList
@EnvironmentObject private var updater: UpdaterType
@EnvironmentObject private var agentStatusChecker: AgentStatusCheckerType
@State private var selectedUpdate: Release?
@State private var showingAppPathNotice = false
@ -30,10 +30,12 @@ struct ContentView: View {
}
.frame(minWidth: 640, minHeight: 320)
.toolbar {
toolbarItem(updateNoticeView, id: "update")
toolbarItem(runningOrRunSetupView, id: "setup")
toolbarItem(appPathNoticeView, id: "appPath")
toolbarItem(newItemView, id: "new")
if #available(macOS 26.0, *) {
toolbarItem(updateNoticeView, id: "update")
toolbarItem(runningOrRunSetupView, id: "setup")
toolbarItem(appPathNoticeView, id: "appPath")
toolbarItem(newItemView, id: "new")
}
}
.sheet(isPresented: $runningSetup) {
SetupView(visible: $runningSetup, setupComplete: $hasRunSetup)
@ -44,9 +46,14 @@ struct ContentView: View {
extension ContentView {
func toolbarItem(_ view: some View, id: String) -> ToolbarItem<String, some View> {
ToolbarItem(id: id) { view }
@ToolbarContentBuilder
func toolbarItem(_ view: some View, id: String) -> some ToolbarContent {
if #available(macOS 26.0, *) {
ToolbarItem(id: id) { view }
.sharedBackgroundVisibility(.hidden)
} else {
ToolbarItem(id: id) { view }
}
}
var needsSetup: Bool {
@ -193,41 +200,41 @@ extension ContentView {
}
//#if DEBUG
//
//struct ContentView_Previews: PreviewProvider {
//
// private static let storeList: SecretStoreList = {
// let list = SecretStoreList()
// list.add(store: SecureEnclave.Store())
// list.add(store: SmartCard.Store())
// return list
// }()
// private static let agentStatusChecker = AgentStatusChecker()
// private static let justUpdatedChecker = JustUpdatedChecker()
//
// @State var hasRunSetup = false
// @State private var showingSetup = false
// @State private var showingCreation = false
//
// static var previews: some View {
// Group {
// // Empty on modifiable and nonmodifiable
// ContentView<PreviewUpdater, AgentStatusChecker>(showingCreation: .constant(false), runningSetup: .constant(false), hasRunSetup: .constant(true))
// .environmentObject(Preview.storeList(stores: [Preview.Store(numberOfRandomSecrets: 0)], modifiableStores: [Preview.StoreModifiable(numberOfRandomSecrets: 0)]))
// .environmentObject(PreviewUpdater())
// .environmentObject(agentStatusChecker)
//
// // 5 items on modifiable and nonmodifiable
// ContentView<PreviewUpdater, AgentStatusChecker>(showingCreation: .constant(false), runningSetup: .constant(false), hasRunSetup: .constant(true))
// .environmentObject(Preview.storeList(stores: [Preview.Store()], modifiableStores: [Preview.StoreModifiable()]))
// .environmentObject(PreviewUpdater())
// .environmentObject(agentStatusChecker)
// }
// .environmentObject(agentStatusChecker)
//
// }
//}
//
//#endif
#if DEBUG
struct ContentView_Previews: PreviewProvider {
private static let storeList: SecretStoreList = {
let list = SecretStoreList()
list.add(store: SecureEnclave.Store())
list.add(store: SmartCard.Store())
return list
}()
private static let agentStatusChecker = AgentStatusChecker()
private static let justUpdatedChecker = JustUpdatedChecker()
@State var hasRunSetup = false
@State private var showingSetup = false
@State private var showingCreation = false
static var previews: some View {
Group {
// Empty on modifiable and nonmodifiable
ContentView<PreviewUpdater, AgentStatusChecker>(showingCreation: .constant(false), runningSetup: .constant(false), hasRunSetup: .constant(true))
.environmentObject(Preview.storeList(stores: [Preview.Store(numberOfRandomSecrets: 0)], modifiableStores: [Preview.StoreModifiable(numberOfRandomSecrets: 0)]))
.environmentObject(PreviewUpdater())
.environmentObject(agentStatusChecker)
// 5 items on modifiable and nonmodifiable
ContentView<PreviewUpdater, AgentStatusChecker>(showingCreation: .constant(false), runningSetup: .constant(false), hasRunSetup: .constant(true))
.environmentObject(Preview.storeList(stores: [Preview.Store()], modifiableStores: [Preview.StoreModifiable()]))
.environmentObject(PreviewUpdater())
.environmentObject(agentStatusChecker)
}
.environmentObject(agentStatusChecker)
}
}
#endif

View File

@ -3,7 +3,7 @@ import SecretKit
struct CreateSecretView<StoreType: SecretStoreModifiable>: View {
@State var store: StoreType
@ObservedObject var store: StoreType
@Binding var showing: Bool
@State private var name = ""
@ -45,10 +45,8 @@ struct CreateSecretView<StoreType: SecretStoreModifiable>: View {
}
func save() {
Task {
try! await store.create(name: name, requiresAuthentication: requiresAuthentication)
showing = false
}
try! store.create(name: name, requiresAuthentication: requiresAuthentication)
showing = false
}
}
@ -232,19 +230,19 @@ struct NotificationView: View {
}
//#if DEBUG
//
//struct CreateSecretView_Previews: PreviewProvider {
//
// static var previews: some View {
// Group {
// CreateSecretView(store: Preview.StoreModifiable(), showing: .constant(true))
// AuthenticationView().environment(\.colorScheme, .dark)
// AuthenticationView().environment(\.colorScheme, .light)
// NotificationView().environment(\.colorScheme, .dark)
// NotificationView().environment(\.colorScheme, .light)
// }
// }
//}
//
//#endif
#if DEBUG
struct CreateSecretView_Previews: PreviewProvider {
static var previews: some View {
Group {
CreateSecretView(store: Preview.StoreModifiable(), showing: .constant(true))
AuthenticationView().environment(\.colorScheme, .dark)
AuthenticationView().environment(\.colorScheme, .light)
NotificationView().environment(\.colorScheme, .dark)
NotificationView().environment(\.colorScheme, .light)
}
}
}
#endif

View File

@ -3,7 +3,7 @@ import SecretKit
struct DeleteSecretView<StoreType: SecretStoreModifiable>: View {
@State var store: StoreType
@ObservedObject var store: StoreType
let secret: StoreType.SecretType
var dismissalBlock: (Bool) -> ()
@ -49,10 +49,8 @@ struct DeleteSecretView<StoreType: SecretStoreModifiable>: View {
}
func delete() {
Task {
try! await store.delete(secret: secret)
dismissalBlock(true)
}
try! store.delete(secret: secret)
dismissalBlock(true)
}
}

View File

@ -3,7 +3,7 @@ import SecretKit
struct EmptyStoreView: View {
@State var store: AnySecretStore
@ObservedObject var store: AnySecretStore
@Binding var activeSecret: AnySecret.ID?
var body: some View {
@ -22,8 +22,8 @@ struct EmptyStoreView: View {
extension EmptyStoreView {
enum Constants {
static let emptyStoreModifiableTag = "emptyStoreModifiableTag"
static let emptyStoreTag = "emptyStoreTag"
static let emptyStoreModifiableTag: AnyHashable = "emptyStoreModifiableTag"
static let emptyStoreTag: AnyHashable = "emptyStoreTag"
}
}

View File

@ -3,7 +3,7 @@ import SecretKit
struct RenameSecretView<StoreType: SecretStoreModifiable>: View {
@State var store: StoreType
@ObservedObject var store: StoreType
let secret: StoreType.SecretType
var dismissalBlock: (_ renamed: Bool) -> ()
@ -44,9 +44,7 @@ struct RenameSecretView<StoreType: SecretStoreModifiable>: View {
}
func rename() {
Task {
try? await store.update(secret: secret, name: newName)
dismissalBlock(true)
}
try? store.update(secret: secret, name: newName)
dismissalBlock(true)
}
}

View File

@ -47,12 +47,12 @@ struct SecretDetailView<SecretType: Secret>: View {
}
//#if DEBUG
//
//struct SecretDetailView_Previews: PreviewProvider {
// static var previews: some View {
// SecretDetailView(secret: Preview.Store(numberOfRandomSecrets: 1).secrets[0])
// }
//}
//
//#endif
#if DEBUG
struct SecretDetailView_Previews: PreviewProvider {
static var previews: some View {
SecretDetailView(secret: Preview.Store(numberOfRandomSecrets: 1).secrets[0])
}
}
#endif

View File

@ -3,7 +3,7 @@ import SecretKit
struct SecretListItemView: View {
@State var store: AnySecretStore
@ObservedObject var store: AnySecretStore
var secret: AnySecret
@Binding var activeSecret: AnySecret.ID?

View File

@ -156,10 +156,8 @@ struct SecretAgentSetupView: View {
}
func install() {
Task {
await LaunchAgentController().install()
buttonAction()
}
LaunchAgentController().install()
buttonAction()
}
}

View File

@ -6,7 +6,7 @@ struct StoreListView: View {
@Binding var activeSecret: AnySecret.ID?
@Environment(SecretStoreList.self) private var storeList: SecretStoreList
@EnvironmentObject private var storeList: SecretStoreList
private func secretDeleted(secret: AnySecret) {
activeSecret = nextDefaultSecret

View File

@ -16,22 +16,44 @@ struct ToolbarButtonStyle: ButtonStyle {
self.lightColor = lightColor
self.darkColor = darkColor
}
private var backingColor: Color {
if !hovering {
colorScheme == .light ? lightColor : darkColor
} else {
colorScheme == .light ? .black.opacity(0.1) : .white.opacity(0.05)
}
}
@Namespace var namespace
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
if #available(macOS 26.0, *) {
configuration
.label
.foregroundColor(.white)
.padding(EdgeInsets(top: 6, leading: 8, bottom: 6, trailing: 8))
.glassEffect(.regular.tint(backingColor), in: .capsule, isEnabled: true)
.onHover { hovering in
withAnimation {
self.hovering = hovering
}
}
}
} else {
configuration
.label
.background(colorScheme == .light ? lightColor : darkColor)
.foregroundColor(.white)
.clipShape(RoundedRectangle(cornerRadius: 5))
.overlay(
RoundedRectangle(cornerRadius: 5)
.stroke(colorScheme == .light ? .black.opacity(0.15) : .white.opacity(0.15), lineWidth: 1)
.background(hovering ? (colorScheme == .light ? .black.opacity(0.1) : .white.opacity(0.05)) : Color.clear)
)
.onHover { hovering in
withAnimation {
self.hovering = hovering
}
}
}
}
}

View File

@ -3,7 +3,7 @@ import Brief
struct UpdateDetailView<UpdaterType: Updater>: View {
@Environment(UpdaterType.self) var updater: UpdaterType
@EnvironmentObject var updater: UpdaterType
let update: Release
@ -18,9 +18,7 @@ struct UpdateDetailView<UpdaterType: Updater>: View {
HStack {
if !update.critical {
Button("update_ignore_button") {
Task {
await updater.ignore(release: update)
}
updater.ignore(release: update)
}
Spacer()
}

View File

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

View File

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