mirror of
https://github.com/maxgoedjen/secretive.git
synced 2025-07-01 09:43:37 +00:00
Compare commits
56 Commits
Author | SHA1 | Date | |
---|---|---|---|
067f1526b0 | |||
f43dea0d0d | |||
db8833fa25 | |||
1409e9ac31 | |||
adabe801d3 | |||
19f9494492 | |||
c50d2feaf9 | |||
03d3cc9177 | |||
141cc03b60 | |||
07559bd7ef | |||
cb206a18c2 | |||
6cb3ff80d9 | |||
05c5aca9b6 | |||
5894bbca00 | |||
3df7ce6256 | |||
b0322b4c1f | |||
7b7615ca38 | |||
da2c460c60 | |||
eb282b4116 | |||
fb6cebe92f | |||
22d9b37d63 | |||
ee3e844519 | |||
3f34e91a2c | |||
f249932ff2 | |||
6eee29e1fa | |||
836aa983ed | |||
9aacd73673 | |||
cda56ea14b | |||
86719e893b | |||
79f7177ffb | |||
6bb9fd376f | |||
7d9fee0546 | |||
faed5514e2 | |||
4ab3783a15 | |||
88b7ef82da | |||
3d305d95ac | |||
3f04126d00 | |||
9d6bbd2a04 | |||
35aea0729d | |||
c5bd4c2189 | |||
8114acf50a | |||
cd965b9ec6 | |||
f30d1f802f | |||
af479408a4 | |||
42b034270a | |||
dca340ad40 | |||
8dfabd35aa | |||
9c28efab5c | |||
698a69a034 | |||
4105c1d6f6 | |||
4de805dd37 | |||
0544287141 | |||
8ec19d1fb7 | |||
6c3748b6bf | |||
dc91f61dba | |||
702388fdf8 |
BIN
.github/readme/app.png
vendored
BIN
.github/readme/app.png
vendored
Binary file not shown.
Before Width: | Height: | Size: 338 KiB After Width: | Height: | Size: 456 KiB |
7
.github/scripts/signing.sh
vendored
7
.github/scripts/signing.sh
vendored
@ -10,10 +10,13 @@ security set-key-partition-list -S apple-tool:,apple:,codesign: -s -k ci ci.keyc
|
||||
|
||||
# Import Profiles
|
||||
mkdir -p ~/Library/MobileDevice/Provisioning\ Profiles
|
||||
|
||||
echo $HOST_PROFILE_DATA | base64 -d -o Host.provisionprofile
|
||||
HOST_UUID=`grep UUID -A1 -a Host.provisionprofile | grep -io "[-A-F0-9]\{36\}"`
|
||||
cp Host.provisionprofile ~/Library/MobileDevice/Provisioning\ Profiles/$HOST_UUID.provisionprofile
|
||||
echo $AGENT_PROFILE_DATA | base64 -d -o Agent.provisionprofile
|
||||
AGENT_UUID=`grep UUID -A1 -a Agent.provisionprofile | grep -io "[-A-F0-9]\{36\}"`
|
||||
cp Agent.provisionprofile ~/Library/MobileDevice/Provisioning\ Profiles/$AGENT_UUID.provisionprofile
|
||||
cp Agent.provisionprofile ~/Library/MobileDevice/Provisioning\ Profiles/$AGENT_UUID.provisionprofile
|
||||
|
||||
# Create directories for ASC key
|
||||
mkdir ~/.private_keys
|
||||
echo -n "$APPLE_API_KEY_DATA" > ~/.private_keys/AuthKey_$APPLE_API_KEY_ID.p8
|
||||
|
49
.github/workflows/nightly.yml
vendored
Normal file
49
.github/workflows/nightly.yml
vendored
Normal file
@ -0,0 +1,49 @@
|
||||
name: Nightly
|
||||
|
||||
on:
|
||||
schedule:
|
||||
- cron: "0 8 * * *"
|
||||
jobs:
|
||||
build:
|
||||
runs-on: macos-11.0
|
||||
timeout-minutes: 10
|
||||
steps:
|
||||
- uses: actions/checkout@v2
|
||||
- name: Setup Signing
|
||||
env:
|
||||
SIGNING_DATA: ${{ secrets.SIGNING_DATA }}
|
||||
SIGNING_PASSWORD: ${{ secrets.SIGNING_PASSWORD }}
|
||||
HOST_PROFILE_DATA: ${{ secrets.HOST_PROFILE_DATA }}
|
||||
AGENT_PROFILE_DATA: ${{ secrets.AGENT_PROFILE_DATA }}
|
||||
APPLE_API_KEY_DATA: ${{ secrets.APPLE_API_KEY_DATA }}
|
||||
APPLE_API_KEY_ID: ${{ secrets.APPLE_API_KEY_ID }}
|
||||
run: ./.github/scripts/signing.sh
|
||||
- name: Set Environment
|
||||
run: sudo xcrun xcode-select -s /Applications/Xcode_13.2.1.app
|
||||
- name: Update Build Number
|
||||
env:
|
||||
RUN_ID: ${{ github.run_id }}
|
||||
run: |
|
||||
sed -i '' -e "s/GITHUB_CI_VERSION/0.0.0/g" Sources/Config/Config.xcconfig
|
||||
sed -i '' -e "s/GITHUB_BUILD_NUMBER/1.$RUN_ID/g" Sources/Config/Config.xcconfig
|
||||
sed -i '' -e "s/GITHUB_BUILD_URL/https:\/\/github.com\/maxgoedjen\/secretive\/actions\/runs\/$RUN_ID/g" Sources/Secretive/Credits.rtf
|
||||
- name: Build
|
||||
run: xcrun xcodebuild -project Sources/Secretive.xcodeproj -scheme Secretive -configuration Release -archivePath Archive.xcarchive archive
|
||||
- name: Create ZIPs
|
||||
run: |
|
||||
ditto -c -k --sequesterRsrc --keepParent Archive.xcarchive/Products/Applications/Secretive.app ./Secretive.zip
|
||||
ditto -c -k --sequesterRsrc --keepParent Archive.xcarchive ./Archive.zip
|
||||
- name: Notarize
|
||||
env:
|
||||
APPLE_API_KEY_ID: ${{ secrets.APPLE_API_KEY_ID }}
|
||||
APPLE_API_ISSUER: ${{ secrets.APPLE_API_ISSUER }}
|
||||
run: xcrun notarytool submit --key ~/.private_keys/AuthKey_$APPLE_API_KEY_ID.p8 --key-id $APPLE_API_KEY_ID --issuer $APPLE_API_ISSUER Secretive.zip
|
||||
- name: Document SHAs
|
||||
run: |
|
||||
shasum -a 512 Secretive.zip
|
||||
shasum -a 512 Archive.zip
|
||||
- name: Upload App to Artifacts
|
||||
uses: actions/upload-artifact@v1
|
||||
with:
|
||||
name: Secretive.zip
|
||||
path: Secretive.zip
|
106
.github/workflows/release.yml
vendored
106
.github/workflows/release.yml
vendored
@ -16,16 +16,56 @@ jobs:
|
||||
SIGNING_PASSWORD: ${{ secrets.SIGNING_PASSWORD }}
|
||||
HOST_PROFILE_DATA: ${{ secrets.HOST_PROFILE_DATA }}
|
||||
AGENT_PROFILE_DATA: ${{ secrets.AGENT_PROFILE_DATA }}
|
||||
APPLE_API_KEY_DATA: ${{ secrets.APPLE_API_KEY_DATA }}
|
||||
APPLE_API_KEY_ID: ${{ secrets.APPLE_API_KEY_ID }}
|
||||
run: ./.github/scripts/signing.sh
|
||||
- name: Set Environment
|
||||
run: sudo xcrun xcode-select -s /Applications/Xcode_12.2.app
|
||||
run: sudo xcrun xcode-select -s /Applications/Xcode_13.2.1.app
|
||||
- name: Test
|
||||
run: xcrun xcodebuild test -project Secretive.xcodeproj -scheme Secretive
|
||||
run: |
|
||||
pushd Sources/Packages
|
||||
swift test
|
||||
popd
|
||||
build:
|
||||
runs-on: macos-11.0
|
||||
timeout-minutes: 10
|
||||
steps:
|
||||
- uses: actions/checkout@v2
|
||||
- name: Setup Signing
|
||||
env:
|
||||
SIGNING_DATA: ${{ secrets.SIGNING_DATA }}
|
||||
SIGNING_PASSWORD: ${{ secrets.SIGNING_PASSWORD }}
|
||||
HOST_PROFILE_DATA: ${{ secrets.HOST_PROFILE_DATA }}
|
||||
AGENT_PROFILE_DATA: ${{ secrets.AGENT_PROFILE_DATA }}
|
||||
APPLE_API_KEY_DATA: ${{ secrets.APPLE_API_KEY_DATA }}
|
||||
APPLE_API_KEY_ID: ${{ secrets.APPLE_API_KEY_ID }}
|
||||
run: ./.github/scripts/signing.sh
|
||||
- name: Set Environment
|
||||
run: sudo xcrun xcode-select -s /Applications/Xcode_13.2.1.app
|
||||
- name: Update Build Number
|
||||
env:
|
||||
TAG_NAME: ${{ github.ref }}
|
||||
RUN_ID: ${{ github.run_id }}
|
||||
run: |
|
||||
export CLEAN_TAG=$(echo $TAG_NAME | sed -e 's/refs\/tags\/v//')
|
||||
sed -i '' -e "s/GITHUB_CI_VERSION/$CLEAN_TAG/g" Sources/Config/Config.xcconfig
|
||||
sed -i '' -e "s/GITHUB_BUILD_NUMBER/1.$RUN_ID/g" Sources/Config/Config.xcconfig
|
||||
sed -i '' -e "s/GITHUB_BUILD_URL/https:\/\/github.com\/maxgoedjen\/secretive\/actions\/runs\/$RUN_ID/g" Sources/Secretive/Credits.rtf
|
||||
- name: Build
|
||||
run: xcrun xcodebuild -project Sources/Secretive.xcodeproj -scheme Secretive -configuration Release -archivePath Archive.xcarchive archive
|
||||
- name: Create ZIPs
|
||||
run: |
|
||||
ditto -c -k --sequesterRsrc --keepParent Archive.xcarchive/Products/Applications/Secretive.app ./Secretive.zip
|
||||
ditto -c -k --sequesterRsrc --keepParent Archive.xcarchive ./Archive.zip
|
||||
- name: Notarize
|
||||
env:
|
||||
APPLE_API_KEY_ID: ${{ secrets.APPLE_API_KEY_ID }}
|
||||
APPLE_API_ISSUER: ${{ secrets.APPLE_API_ISSUER }}
|
||||
run: xcrun notarytool submit --key ~/.private_keys/AuthKey_$APPLE_API_KEY_ID.p8 --key-id $APPLE_API_KEY_ID --issuer $APPLE_API_ISSUER Secretive.zip
|
||||
- name: Document SHAs
|
||||
run: |
|
||||
shasum -a 512 Secretive.zip
|
||||
shasum -a 512 Archive.zip
|
||||
- name: Create Release
|
||||
id: create_release
|
||||
uses: actions/create-release@v1
|
||||
@ -34,44 +74,24 @@ jobs:
|
||||
with:
|
||||
tag_name: ${{ github.ref }}
|
||||
release_name: ${{ github.ref }}
|
||||
body: "## Build\nhttps://github.com/maxgoedjen/secretive/actions/runs/${{ github.run_id }}"
|
||||
body: |
|
||||
Update description
|
||||
|
||||
## Features
|
||||
|
||||
|
||||
## Fixes
|
||||
|
||||
|
||||
## Minimum macOS Version
|
||||
|
||||
|
||||
## Build
|
||||
https://github.com/maxgoedjen/secretive/actions/runs/${{ github.run_id }}
|
||||
draft: true
|
||||
prerelease: false
|
||||
- name: Setup Signing
|
||||
env:
|
||||
SIGNING_DATA: ${{ secrets.SIGNING_DATA }}
|
||||
SIGNING_PASSWORD: ${{ secrets.SIGNING_PASSWORD }}
|
||||
HOST_PROFILE_DATA: ${{ secrets.HOST_PROFILE_DATA }}
|
||||
AGENT_PROFILE_DATA: ${{ secrets.AGENT_PROFILE_DATA }}
|
||||
run: ./.github/scripts/signing.sh
|
||||
- name: Set Environment
|
||||
run: sudo xcrun xcode-select -s /Applications/Xcode_12.2.app
|
||||
- name: Update Build Number
|
||||
env:
|
||||
TAG_NAME: ${{ github.ref }}
|
||||
RUN_ID: ${{ github.run_id }}
|
||||
run: |
|
||||
export CLEAN_TAG=$(echo $TAG_NAME | sed -e 's/refs\/tags\/v//')
|
||||
sed -i '' -e "s/GITHUB_CI_VERSION/$CLEAN_TAG/g" Config/Config.xcconfig
|
||||
sed -i '' -e "s/GITHUB_BUILD_NUMBER/1.$RUN_ID/g" Config/Config.xcconfig
|
||||
sed -i '' -e "s/GITHUB_BUILD_URL/https:\/\/github.com\/maxgoedjen\/secretive\/actions\/runs\/$RUN_ID/g" Secretive/Credits.rtf
|
||||
- name: Build
|
||||
run: xcrun xcodebuild -project Secretive.xcodeproj -scheme Secretive -configuration Release -archivePath Archive.xcarchive archive
|
||||
- name: Create ZIPs
|
||||
run: |
|
||||
ditto -c -k --sequesterRsrc --keepParent Archive.xcarchive/Products/Applications/Secretive.app ./Secretive.zip
|
||||
ditto -c -k --sequesterRsrc --keepParent Archive.xcarchive ./Archive.zip
|
||||
- name: Notarize
|
||||
env:
|
||||
APPLE_USERNAME: ${{ secrets.APPLE_USERNAME }}
|
||||
APPLE_PASSWORD: ${{ secrets.APPLE_PASSWORD }}
|
||||
run: xcrun altool --notarize-app --primary-bundle-id "com.maxgoedjen.secretive.host" --username $APPLE_USERNAME --password $APPLE_PASSWORD --file Secretive.zip
|
||||
- name: Document SHAs
|
||||
run: |
|
||||
shasum -a 512 Secretive.zip
|
||||
shasum -a 512 Archive.zip
|
||||
- name: Upload App to Release
|
||||
id: upload-release-asset
|
||||
id: upload-release-asset-app
|
||||
uses: actions/upload-release-asset@v1.0.1
|
||||
env:
|
||||
GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }}
|
||||
@ -80,13 +100,13 @@ jobs:
|
||||
asset_path: ./Secretive.zip
|
||||
asset_name: Secretive.zip
|
||||
asset_content_type: application/zip
|
||||
- name: Upload Archive to Artifacts
|
||||
uses: actions/upload-artifact@v1
|
||||
with:
|
||||
name: Archive.zip
|
||||
path: Archive.zip
|
||||
- name: Upload Archive to Artifacts
|
||||
- name: Upload App to Artifacts
|
||||
uses: actions/upload-artifact@v1
|
||||
with:
|
||||
name: Secretive.zip
|
||||
path: Secretive.zip
|
||||
- name: Upload Archive to Artifacts
|
||||
uses: actions/upload-artifact@v1
|
||||
with:
|
||||
name: Xcode_Archive.zip
|
||||
path: Archive.zip
|
||||
|
7
.github/workflows/test.yml
vendored
7
.github/workflows/test.yml
vendored
@ -8,6 +8,9 @@ jobs:
|
||||
steps:
|
||||
- uses: actions/checkout@v2
|
||||
- name: Set Environment
|
||||
run: sudo xcrun xcode-select -s /Applications/Xcode_12.2.app
|
||||
run: sudo xcrun xcode-select -s /Applications/Xcode_13.2.1.app
|
||||
- name: Test
|
||||
run: xcrun xcodebuild test -project Secretive.xcodeproj -scheme Secretive
|
||||
run: |
|
||||
pushd Sources/Packages
|
||||
swift test
|
||||
popd
|
||||
|
1
.gitignore
vendored
1
.gitignore
vendored
@ -92,3 +92,4 @@ iOSInjectionProject/
|
||||
# Build script products
|
||||
Archive.xcarchive
|
||||
.DS_Store
|
||||
contents.xcworkspacedata
|
||||
|
@ -26,8 +26,57 @@ Host *
|
||||
IdentityAgent /Users/$YOUR_USERNAME/Library/Containers/com.maxgoedjen.Secretive.SecretAgent/Data/socket.ssh
|
||||
```
|
||||
|
||||
## Cyberduck
|
||||
|
||||
Add this to `~/Library/LaunchAgents/com.maxgoedjen.Secretive.SecretAgent.plist`
|
||||
|
||||
```
|
||||
<?xml version="1.0" encoding="UTF-8"?>
|
||||
<!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd">
|
||||
<plist version="1.0">
|
||||
<dict>
|
||||
<key>Label</key>
|
||||
<string>link-ssh-auth-sock</string>
|
||||
<key>ProgramArguments</key>
|
||||
<array>
|
||||
<string>/bin/sh</string>
|
||||
<string>-c</string>
|
||||
<string>/bin/ln -sf $HOME/Library/Containers/com.maxgoedjen.Secretive.SecretAgent/Data/socket.ssh $SSH_AUTH_SOCK</string>
|
||||
</array>
|
||||
<key>RunAtLoad</key>
|
||||
<true/>
|
||||
</dict>
|
||||
</plist>
|
||||
```
|
||||
|
||||
Log out and log in again before launching Cyberduck.
|
||||
|
||||
## GitKraken
|
||||
|
||||
Add this to `~/Library/LaunchAgents/com.maxgoedjen.Secretive.SecretAgent.plist`
|
||||
|
||||
```
|
||||
<?xml version="1.0" encoding="UTF-8"?>
|
||||
<!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd">
|
||||
<plist version="1.0">
|
||||
<dict>
|
||||
<key>Label</key>
|
||||
<string>link-ssh-auth-sock</string>
|
||||
<key>ProgramArguments</key>
|
||||
<array>
|
||||
<string>/bin/sh</string>
|
||||
<string>-c</string>
|
||||
<string>/bin/ln -sf $HOME/Library/Containers/com.maxgoedjen.Secretive.SecretAgent/Data/socket.ssh $SSH_AUTH_SOCK</string>
|
||||
</array>
|
||||
<key>RunAtLoad</key>
|
||||
<true/>
|
||||
</dict>
|
||||
</plist>
|
||||
```
|
||||
|
||||
Log out and log in again before launching Gitkraken. Then enable "Use local SSH agent in GitKraken Preferences (Located under Preferences -> SSH)
|
||||
|
||||
# The app I use isn't listed here!
|
||||
|
||||
If you know how to get it set up, please open a PR for this page and add it! Contributions are very welcome.
|
||||
If you're not able to get it working, please file a [GitHub issue](https://github.com/maxgoedjen/secretive/issues/new) for it. No guarantees we'll be able to get it working, but chances are someone else in the community might be able to.
|
||||
If you're not able to get it working, please file a [GitHub issue](https://github.com/maxgoedjen/secretive/issues/new) for it. No guarantees we'll be able to get it working, but chances are someone else in the community might be able to.
|
||||
|
@ -1,19 +0,0 @@
|
||||
//
|
||||
// Brief.h
|
||||
// Brief
|
||||
//
|
||||
// Created by Max Goedjen on 3/21/20.
|
||||
// Copyright © 2020 Max Goedjen. All rights reserved.
|
||||
//
|
||||
|
||||
#import <Foundation/Foundation.h>
|
||||
|
||||
//! Project version number for Brief.
|
||||
FOUNDATION_EXPORT double BriefVersionNumber;
|
||||
|
||||
//! Project version string for Brief.
|
||||
FOUNDATION_EXPORT const unsigned char BriefVersionString[];
|
||||
|
||||
// In this header, you should import all the public headers of your framework using statements like #import <Brief/PublicHeader.h>
|
||||
|
||||
|
@ -1,24 +0,0 @@
|
||||
<?xml version="1.0" encoding="UTF-8"?>
|
||||
<!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd">
|
||||
<plist version="1.0">
|
||||
<dict>
|
||||
<key>CFBundleDevelopmentRegion</key>
|
||||
<string>$(DEVELOPMENT_LANGUAGE)</string>
|
||||
<key>CFBundleExecutable</key>
|
||||
<string>$(EXECUTABLE_NAME)</string>
|
||||
<key>CFBundleIdentifier</key>
|
||||
<string>$(PRODUCT_BUNDLE_IDENTIFIER)</string>
|
||||
<key>CFBundleInfoDictionaryVersion</key>
|
||||
<string>6.0</string>
|
||||
<key>CFBundleName</key>
|
||||
<string>$(PRODUCT_NAME)</string>
|
||||
<key>CFBundlePackageType</key>
|
||||
<string>$(PRODUCT_BUNDLE_PACKAGE_TYPE)</string>
|
||||
<key>CFBundleShortVersionString</key>
|
||||
<string>1.0</string>
|
||||
<key>CFBundleVersion</key>
|
||||
<string>$(CURRENT_PROJECT_VERSION)</string>
|
||||
<key>NSHumanReadableCopyright</key>
|
||||
<string>$(PRODUCT_NAME) is MIT Licensed.</string>
|
||||
</dict>
|
||||
</plist>
|
@ -1,145 +0,0 @@
|
||||
import Foundation
|
||||
import Combine
|
||||
|
||||
public protocol UpdaterProtocol: ObservableObject {
|
||||
|
||||
var update: Release? { get }
|
||||
|
||||
}
|
||||
|
||||
public class Updater: ObservableObject, UpdaterProtocol {
|
||||
|
||||
@Published public var update: Release?
|
||||
|
||||
public init(checkOnLaunch: Bool) {
|
||||
if checkOnLaunch {
|
||||
// Don't do a launch check if the user hasn't seen the setup prompt explaining updater yet.
|
||||
checkForUpdates()
|
||||
}
|
||||
let timer = Timer.scheduledTimer(withTimeInterval: 60*60*24, repeats: true) { _ in
|
||||
self.checkForUpdates()
|
||||
}
|
||||
timer.tolerance = 60*60
|
||||
}
|
||||
|
||||
public func checkForUpdates() {
|
||||
URLSession.shared.dataTask(with: Constants.updateURL) { data, _, _ in
|
||||
guard let data = data else { return }
|
||||
guard let release = try? JSONDecoder().decode(Release.self, from: data) else { return }
|
||||
self.evaluate(release: release)
|
||||
}.resume()
|
||||
}
|
||||
|
||||
public func ignore(release: Release) {
|
||||
guard !release.critical else { return }
|
||||
defaults.set(true, forKey: release.name)
|
||||
DispatchQueue.main.async {
|
||||
self.update = nil
|
||||
}
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
extension Updater {
|
||||
|
||||
func evaluate(release: Release) {
|
||||
guard !userIgnored(release: release) else { return }
|
||||
guard !release.prerelease else { return }
|
||||
let latestVersion = SemVer(release.name)
|
||||
let currentVersion = SemVer(Bundle.main.infoDictionary!["CFBundleShortVersionString"] as! String)
|
||||
if latestVersion > currentVersion {
|
||||
DispatchQueue.main.async {
|
||||
self.update = release
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func userIgnored(release: Release) -> Bool {
|
||||
guard !release.critical else { return false }
|
||||
return defaults.bool(forKey: release.name)
|
||||
}
|
||||
|
||||
var defaults: UserDefaults {
|
||||
UserDefaults(suiteName: "com.maxgoedjen.Secretive.updater.ignorelist")!
|
||||
}
|
||||
}
|
||||
|
||||
struct SemVer {
|
||||
|
||||
let versionNumbers: [Int]
|
||||
|
||||
init(_ version: String) {
|
||||
// Betas have the format 1.2.3_beta1
|
||||
let strippedBeta = version.split(separator: "_").first!
|
||||
var split = strippedBeta.split(separator: ".").compactMap { Int($0) }
|
||||
while split.count < 3 {
|
||||
split.append(0)
|
||||
}
|
||||
versionNumbers = split
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
extension SemVer: Comparable {
|
||||
|
||||
static func < (lhs: SemVer, rhs: SemVer) -> Bool {
|
||||
for (latest, current) in zip(lhs.versionNumbers, rhs.versionNumbers) {
|
||||
if latest < current {
|
||||
return true
|
||||
} else if latest > current {
|
||||
return false
|
||||
}
|
||||
}
|
||||
return false
|
||||
}
|
||||
|
||||
|
||||
}
|
||||
|
||||
extension Updater {
|
||||
|
||||
enum Constants {
|
||||
static let updateURL = URL(string: "https://api.github.com/repos/maxgoedjen/secretive/releases/latest")!
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
public struct Release: Codable {
|
||||
|
||||
public let name: String
|
||||
public let prerelease: Bool
|
||||
public let html_url: URL
|
||||
public let body: String
|
||||
|
||||
public init(name: String, prerelease: Bool, html_url: URL, body: String) {
|
||||
self.name = name
|
||||
self.prerelease = prerelease
|
||||
self.html_url = html_url
|
||||
self.body = body
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
extension Release: Identifiable {
|
||||
|
||||
public var id: String {
|
||||
html_url.absoluteString
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
extension Release {
|
||||
|
||||
public var critical: Bool {
|
||||
body.contains(Constants.securityContent)
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
extension Release {
|
||||
|
||||
enum Constants {
|
||||
static let securityContent = "Critical Security Update"
|
||||
}
|
||||
|
||||
}
|
@ -14,6 +14,14 @@ Secretive is designed to be easily auditable by people who are considering using
|
||||
|
||||
All contributors must abide by the [Code of Conduct](CODE_OF_CONDUCT.md)
|
||||
|
||||
## Credits
|
||||
|
||||
If you make a material contribution to the app, please add yourself to the end of the [credits](https://github.com/maxgoedjen/secretive/blob/main/Secretive/Credits.rtf).
|
||||
|
||||
## Collaborator Status
|
||||
|
||||
I will not grant collaborator access to any contributors for this repository. This is basically just because collaborators [can accesss the secrets Secretive uses for the signing credentials stored in the repository](https://docs.github.com/en/actions/reference/encrypted-secrets#accessing-your-secrets).
|
||||
|
||||
## Secretive is Opinionated
|
||||
|
||||
I'm releasing Secretive as open source so that other people can use it and audit it, feeling comfortable in knowing that the source is available so they can see what it's doing. I have a pretty strong idea of what I'd like this project to look like, and I may respectfully decline contributions that don't line up with that vision. If you'd like to propose a change before implementing, please feel free to [Open an Issue with the proposed tag](https://github.com/maxgoedjen/secretive/issues/new?labels=proposed).
|
||||
|
@ -1,50 +0,0 @@
|
||||
{
|
||||
"configurations" : [
|
||||
{
|
||||
"id" : "5896AE5A-6D5A-48D3-837B-668B646A3273",
|
||||
"name" : "Configuration 1",
|
||||
"options" : {
|
||||
|
||||
}
|
||||
}
|
||||
],
|
||||
"defaultOptions" : {
|
||||
|
||||
},
|
||||
"testTargets" : [
|
||||
{
|
||||
"parallelizable" : true,
|
||||
"target" : {
|
||||
"containerPath" : "container:Secretive.xcodeproj",
|
||||
"identifier" : "50617DAF23FCE4AB0099B055",
|
||||
"name" : "SecretKitTests"
|
||||
}
|
||||
},
|
||||
{
|
||||
"parallelizable" : true,
|
||||
"target" : {
|
||||
"containerPath" : "container:Secretive.xcodeproj",
|
||||
"identifier" : "5099A073240242BA0062B6F2",
|
||||
"name" : "SecretAgentKitTests"
|
||||
}
|
||||
},
|
||||
{
|
||||
"enabled" : false,
|
||||
"parallelizable" : true,
|
||||
"target" : {
|
||||
"containerPath" : "container:Secretive.xcodeproj",
|
||||
"identifier" : "50617D9323FCE48E0099B055",
|
||||
"name" : "SecretiveTests"
|
||||
}
|
||||
},
|
||||
{
|
||||
"parallelizable" : true,
|
||||
"target" : {
|
||||
"containerPath" : "container:Secretive.xcodeproj",
|
||||
"identifier" : "5091D31E2519D56D0049FD9B",
|
||||
"name" : "BriefTests"
|
||||
}
|
||||
}
|
||||
],
|
||||
"version" : 1
|
||||
}
|
3
DESIGN.md
Normal file
3
DESIGN.md
Normal file
@ -0,0 +1,3 @@
|
||||
# Design
|
||||
|
||||
The art assets for the App Icon and GitHub image are located on [Sketch Cloud](https://www.sketch.com/s/574333cd-8ceb-40e1-a6d9-189da3f1e5dd).
|
10
FAQ.md
10
FAQ.md
@ -24,6 +24,10 @@ Please run `ssh -Tv git@github.com` in your terminal and paste the output in a [
|
||||

|
||||

|
||||
|
||||
### How do I tell SSH to use a specific key?
|
||||
|
||||
You can create a `mykey.pub` (where `mykey` is the name of your key) in your `~/.ssh/` directory with the contents of your public key, and specify that you want to use that key in your `~/.ssh/config`. [This ServerFault answer](https://serverfault.com/a/295771) has more details on setting that up
|
||||
|
||||
### Why should I trust you?
|
||||
|
||||
You shouldn't, for a piece of software like this. Secretive, by design, has an auditable build process. Each build has a fully auditable build log, showing the source it was built from and a SHA of the build product. You can check the SHA of the zip you download against the SHA output in the build log (which is linked in the About window).
|
||||
@ -34,7 +38,11 @@ Awesome! Just bear in mind that because an app only has access to the keychain i
|
||||
|
||||
### What's this network request to GitHub?
|
||||
|
||||
Secretive checks in with GitHub's releases API to check if there's a new version of Secretive available. You can audit the source code for this feature [here](https://github.com/maxgoedjen/secretive/blob/main/Brief/Updater.swift).
|
||||
Secretive checks in with GitHub's releases API to check if there's a new version of Secretive available. You can audit the source code for this feature [here](https://github.com/maxgoedjen/secretive/blob/main/Sources/Packages/Sources/Brief/Updater.swift).
|
||||
|
||||
### How do I uninstall Secretive?
|
||||
|
||||
Drag Secretive.app to the trash and remove `~/Library/Containers/com.maxgoedjen.Secretive.SecretAgent`. `SecretAgent` may continue running until you quit it or reboot.
|
||||
|
||||
### I have a security issue
|
||||
|
||||
|
BIN
Icon.sketch
BIN
Icon.sketch
Binary file not shown.
@ -38,7 +38,7 @@ You can download the latest release over on the [Releases Page](https://github.c
|
||||
|
||||
#### Using Homebrew
|
||||
|
||||
brew cask install secretive
|
||||
brew install secretive
|
||||
|
||||
### FAQ
|
||||
|
||||
|
@ -1,105 +0,0 @@
|
||||
import Foundation
|
||||
import UserNotifications
|
||||
import AppKit
|
||||
import SecretKit
|
||||
import SecretAgentKit
|
||||
import Brief
|
||||
|
||||
class Notifier {
|
||||
|
||||
private let notificationDelegate = NotificationDelegate()
|
||||
|
||||
init() {
|
||||
let updateAction = UNNotificationAction(identifier: Constants.updateActionIdentitifier, title: "Update", options: [])
|
||||
let ignoreAction = UNNotificationAction(identifier: Constants.ignoreActionIdentitifier, title: "Ignore", options: [])
|
||||
let updateCategory = UNNotificationCategory(identifier: Constants.updateCategoryIdentitifier, actions: [updateAction, ignoreAction], intentIdentifiers: [], options: [])
|
||||
let criticalUpdateCategory = UNNotificationCategory(identifier: Constants.criticalUpdateCategoryIdentitifier, actions: [updateAction], intentIdentifiers: [], options: [])
|
||||
UNUserNotificationCenter.current().setNotificationCategories([updateCategory, criticalUpdateCategory])
|
||||
UNUserNotificationCenter.current().delegate = notificationDelegate
|
||||
}
|
||||
|
||||
func prompt() {
|
||||
let notificationCenter = UNUserNotificationCenter.current()
|
||||
notificationCenter.requestAuthorization(options: .alert) { _, _ in }
|
||||
}
|
||||
|
||||
func notify(accessTo secret: AnySecret, by provenance: SigningRequestProvenance) {
|
||||
let notificationCenter = UNUserNotificationCenter.current()
|
||||
let notificationContent = UNMutableNotificationContent()
|
||||
notificationContent.title = "Signed Request from \(provenance.origin.displayName)"
|
||||
notificationContent.subtitle = "Using secret \"\(secret.name)\""
|
||||
if let iconURL = provenance.origin.iconURL, let attachment = try? UNNotificationAttachment(identifier: "icon", url: iconURL, options: nil) {
|
||||
notificationContent.attachments = [attachment]
|
||||
}
|
||||
let request = UNNotificationRequest(identifier: UUID().uuidString, content: notificationContent, trigger: nil)
|
||||
notificationCenter.add(request, withCompletionHandler: nil)
|
||||
}
|
||||
|
||||
func notify(update: Release, ignore: ((Release) -> Void)?) {
|
||||
notificationDelegate.release = update
|
||||
notificationDelegate.ignore = ignore
|
||||
let notificationCenter = UNUserNotificationCenter.current()
|
||||
let notificationContent = UNMutableNotificationContent()
|
||||
if update.critical {
|
||||
notificationContent.title = "Critical Security Update - \(update.name)"
|
||||
} else {
|
||||
notificationContent.title = "Update Available - \(update.name)"
|
||||
}
|
||||
notificationContent.subtitle = "Click to Update"
|
||||
notificationContent.body = update.body
|
||||
notificationContent.categoryIdentifier = update.critical ? Constants.criticalUpdateCategoryIdentitifier : Constants.updateCategoryIdentitifier
|
||||
let request = UNNotificationRequest(identifier: UUID().uuidString, content: notificationContent, trigger: nil)
|
||||
notificationCenter.add(request, withCompletionHandler: nil)
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
extension Notifier: SigningWitness {
|
||||
|
||||
func speakNowOrForeverHoldYourPeace(forAccessTo secret: AnySecret, by provenance: SigningRequestProvenance) throws {
|
||||
}
|
||||
|
||||
func witness(accessTo secret: AnySecret, by provenance: SigningRequestProvenance) throws {
|
||||
notify(accessTo: secret, by: provenance)
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
extension Notifier {
|
||||
|
||||
enum Constants {
|
||||
static let updateCategoryIdentitifier = "com.maxgoedjen.Secretive.SecretAgent.update"
|
||||
static let criticalUpdateCategoryIdentitifier = "com.maxgoedjen.Secretive.SecretAgent.update.critical"
|
||||
static let updateActionIdentitifier = "com.maxgoedjen.Secretive.SecretAgent.update.updateaction"
|
||||
static let ignoreActionIdentitifier = "com.maxgoedjen.Secretive.SecretAgent.update.ignoreaction"
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
class NotificationDelegate: NSObject, UNUserNotificationCenterDelegate {
|
||||
|
||||
fileprivate var release: Release?
|
||||
fileprivate var ignore: ((Release) -> Void)?
|
||||
|
||||
func userNotificationCenter(_ center: UNUserNotificationCenter, openSettingsFor notification: UNNotification?) {
|
||||
|
||||
}
|
||||
|
||||
func userNotificationCenter(_ center: UNUserNotificationCenter, didReceive response: UNNotificationResponse, withCompletionHandler completionHandler: @escaping () -> Void) {
|
||||
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()
|
||||
}
|
||||
completionHandler()
|
||||
}
|
||||
|
||||
func userNotificationCenter(_ center: UNUserNotificationCenter, willPresent notification: UNNotification, withCompletionHandler completionHandler: @escaping (UNNotificationPresentationOptions) -> Void) {
|
||||
completionHandler([.list, .banner])
|
||||
}
|
||||
|
||||
}
|
@ -1,24 +0,0 @@
|
||||
<?xml version="1.0" encoding="UTF-8"?>
|
||||
<!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd">
|
||||
<plist version="1.0">
|
||||
<dict>
|
||||
<key>CFBundleDevelopmentRegion</key>
|
||||
<string>$(DEVELOPMENT_LANGUAGE)</string>
|
||||
<key>CFBundleExecutable</key>
|
||||
<string>$(EXECUTABLE_NAME)</string>
|
||||
<key>CFBundleIdentifier</key>
|
||||
<string>$(PRODUCT_BUNDLE_IDENTIFIER)</string>
|
||||
<key>CFBundleInfoDictionaryVersion</key>
|
||||
<string>6.0</string>
|
||||
<key>CFBundleName</key>
|
||||
<string>$(PRODUCT_NAME)</string>
|
||||
<key>CFBundlePackageType</key>
|
||||
<string>$(PRODUCT_BUNDLE_PACKAGE_TYPE)</string>
|
||||
<key>CFBundleShortVersionString</key>
|
||||
<string>$(CI_VERSION)</string>
|
||||
<key>CFBundleVersion</key>
|
||||
<string>$(CURRENT_PROJECT_VERSION)</string>
|
||||
<key>NSHumanReadableCopyright</key>
|
||||
<string>$(PRODUCT_NAME) is MIT Licensed.</string>
|
||||
</dict>
|
||||
</plist>
|
@ -1,9 +0,0 @@
|
||||
import Foundation
|
||||
import SecretKit
|
||||
|
||||
public protocol SigningWitness {
|
||||
|
||||
func speakNowOrForeverHoldYourPeace(forAccessTo secret: AnySecret, by provenance: SigningRequestProvenance) throws
|
||||
func witness(accessTo secret: AnySecret, by provenance: SigningRequestProvenance) throws
|
||||
|
||||
}
|
@ -1,22 +0,0 @@
|
||||
<?xml version="1.0" encoding="UTF-8"?>
|
||||
<!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd">
|
||||
<plist version="1.0">
|
||||
<dict>
|
||||
<key>CFBundleDevelopmentRegion</key>
|
||||
<string>$(DEVELOPMENT_LANGUAGE)</string>
|
||||
<key>CFBundleExecutable</key>
|
||||
<string>$(EXECUTABLE_NAME)</string>
|
||||
<key>CFBundleIdentifier</key>
|
||||
<string>$(PRODUCT_BUNDLE_IDENTIFIER)</string>
|
||||
<key>CFBundleInfoDictionaryVersion</key>
|
||||
<string>6.0</string>
|
||||
<key>CFBundleName</key>
|
||||
<string>$(PRODUCT_NAME)</string>
|
||||
<key>CFBundlePackageType</key>
|
||||
<string>$(PRODUCT_BUNDLE_PACKAGE_TYPE)</string>
|
||||
<key>CFBundleShortVersionString</key>
|
||||
<string>1.0</string>
|
||||
<key>CFBundleVersion</key>
|
||||
<string>1</string>
|
||||
</dict>
|
||||
</plist>
|
@ -1,49 +0,0 @@
|
||||
import Foundation
|
||||
import CryptoKit
|
||||
|
||||
// For the moment, only supports ecdsa-sha2-nistp256 and ecdsa-sha2-nistp386 keys
|
||||
public struct OpenSSHKeyWriter {
|
||||
|
||||
public init() {
|
||||
}
|
||||
|
||||
public func data<SecretType: Secret>(secret: SecretType) -> Data {
|
||||
lengthAndData(of: curveType(for: secret.algorithm, length: secret.keySize).data(using: .utf8)!) +
|
||||
lengthAndData(of: curveIdentifier(for: secret.algorithm, length: secret.keySize).data(using: .utf8)!) +
|
||||
lengthAndData(of: secret.publicKey)
|
||||
}
|
||||
|
||||
public func openSSHString<SecretType: Secret>(secret: SecretType) -> String {
|
||||
"\(curveType(for: secret.algorithm, length: secret.keySize)) \(data(secret: secret).base64EncodedString())"
|
||||
}
|
||||
|
||||
public func openSSHFingerprint<SecretType: Secret>(secret: SecretType) -> String {
|
||||
Insecure.MD5.hash(data: data(secret: secret))
|
||||
.compactMap { ("0" + String($0, radix: 16, uppercase: false)).suffix(2) }
|
||||
.joined(separator: ":")
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
extension OpenSSHKeyWriter {
|
||||
|
||||
public func lengthAndData(of data: Data) -> Data {
|
||||
let rawLength = UInt32(data.count)
|
||||
var endian = rawLength.bigEndian
|
||||
return Data(bytes: &endian, count: UInt32.bitWidth/8) + data
|
||||
}
|
||||
|
||||
public func curveIdentifier(for algorithm: Algorithm, length: Int) -> String {
|
||||
switch algorithm {
|
||||
case .ellipticCurve:
|
||||
return "nistp" + String(describing: length)
|
||||
}
|
||||
}
|
||||
|
||||
public func curveType(for algorithm: Algorithm, length: Int) -> String {
|
||||
switch algorithm {
|
||||
case .ellipticCurve:
|
||||
return "ecdsa-sha2-nistp" + String(describing: length)
|
||||
}
|
||||
}
|
||||
}
|
@ -1,27 +0,0 @@
|
||||
import Combine
|
||||
|
||||
public protocol SecretStore: ObservableObject, Identifiable {
|
||||
|
||||
associatedtype SecretType: Secret
|
||||
|
||||
var isAvailable: Bool { get }
|
||||
var id: UUID { get }
|
||||
var name: String { get }
|
||||
var secrets: [SecretType] { get }
|
||||
|
||||
func sign(data: Data, with secret: SecretType, for provenance: SigningRequestProvenance) throws -> Data
|
||||
|
||||
}
|
||||
|
||||
public protocol SecretStoreModifiable: SecretStore {
|
||||
|
||||
func create(name: String, requiresAuthentication: Bool) throws
|
||||
func delete(secret: SecretType) throws
|
||||
|
||||
}
|
||||
|
||||
extension NSNotification.Name {
|
||||
|
||||
static let secretStoreUpdated = NSNotification.Name("com.maxgoedjen.Secretive.secretStore.updated")
|
||||
|
||||
}
|
@ -1,53 +0,0 @@
|
||||
import Foundation
|
||||
import AppKit
|
||||
|
||||
public struct SigningRequestProvenance: Equatable {
|
||||
|
||||
public var chain: [Process]
|
||||
public init(root: Process) {
|
||||
self.chain = [root]
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
extension SigningRequestProvenance {
|
||||
|
||||
public var origin: Process {
|
||||
chain.last!
|
||||
}
|
||||
|
||||
public var intact: Bool {
|
||||
chain.allSatisfy { $0.validSignature }
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
extension SigningRequestProvenance {
|
||||
|
||||
public struct Process: Equatable {
|
||||
|
||||
public let pid: Int32
|
||||
public let processName: String
|
||||
public let appName: String?
|
||||
public let iconURL: URL?
|
||||
public let path: String
|
||||
public let validSignature: Bool
|
||||
public let parentPID: Int32?
|
||||
|
||||
public init(pid: Int32, processName: String, appName: String?, iconURL: URL?, path: String, validSignature: Bool, parentPID: Int32?) {
|
||||
self.pid = pid
|
||||
self.processName = processName
|
||||
self.appName = appName
|
||||
self.iconURL = iconURL
|
||||
self.path = path
|
||||
self.validSignature = validSignature
|
||||
self.parentPID = parentPID
|
||||
}
|
||||
|
||||
public var displayName: String {
|
||||
appName ?? processName
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
}
|
@ -1,24 +0,0 @@
|
||||
<?xml version="1.0" encoding="UTF-8"?>
|
||||
<!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd">
|
||||
<plist version="1.0">
|
||||
<dict>
|
||||
<key>CFBundleDevelopmentRegion</key>
|
||||
<string>$(DEVELOPMENT_LANGUAGE)</string>
|
||||
<key>CFBundleExecutable</key>
|
||||
<string>$(EXECUTABLE_NAME)</string>
|
||||
<key>CFBundleIdentifier</key>
|
||||
<string>$(PRODUCT_BUNDLE_IDENTIFIER)</string>
|
||||
<key>CFBundleInfoDictionaryVersion</key>
|
||||
<string>6.0</string>
|
||||
<key>CFBundleName</key>
|
||||
<string>$(PRODUCT_NAME)</string>
|
||||
<key>CFBundlePackageType</key>
|
||||
<string>$(PRODUCT_BUNDLE_PACKAGE_TYPE)</string>
|
||||
<key>CFBundleShortVersionString</key>
|
||||
<string>$(CI_VERSION)</string>
|
||||
<key>CFBundleVersion</key>
|
||||
<string>$(CURRENT_PROJECT_VERSION)</string>
|
||||
<key>NSHumanReadableCopyright</key>
|
||||
<string>$(PRODUCT_NAME) is MIT Licensed.</string>
|
||||
</dict>
|
||||
</plist>
|
@ -1,11 +0,0 @@
|
||||
#import <Foundation/Foundation.h>
|
||||
|
||||
//! Project version number for SecretKit.
|
||||
FOUNDATION_EXPORT double SecretKitVersionNumber;
|
||||
|
||||
//! Project version string for SecretKit.
|
||||
FOUNDATION_EXPORT const unsigned char SecretKitVersionString[];
|
||||
|
||||
// In this header, you should import all the public headers of your framework using statements like #import <SecretKit/PublicHeader.h>
|
||||
|
||||
|
@ -1 +0,0 @@
|
||||
public enum SecureEnclave {}
|
@ -1 +0,0 @@
|
||||
public enum SmartCard {}
|
@ -1,22 +0,0 @@
|
||||
<?xml version="1.0" encoding="UTF-8"?>
|
||||
<!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd">
|
||||
<plist version="1.0">
|
||||
<dict>
|
||||
<key>CFBundleDevelopmentRegion</key>
|
||||
<string>$(DEVELOPMENT_LANGUAGE)</string>
|
||||
<key>CFBundleExecutable</key>
|
||||
<string>$(EXECUTABLE_NAME)</string>
|
||||
<key>CFBundleIdentifier</key>
|
||||
<string>$(PRODUCT_BUNDLE_IDENTIFIER)</string>
|
||||
<key>CFBundleInfoDictionaryVersion</key>
|
||||
<string>6.0</string>
|
||||
<key>CFBundleName</key>
|
||||
<string>$(PRODUCT_NAME)</string>
|
||||
<key>CFBundlePackageType</key>
|
||||
<string>$(PRODUCT_BUNDLE_PACKAGE_TYPE)</string>
|
||||
<key>CFBundleShortVersionString</key>
|
||||
<string>1.0</string>
|
||||
<key>CFBundleVersion</key>
|
||||
<string>1</string>
|
||||
</dict>
|
||||
</plist>
|
File diff suppressed because it is too large
Load Diff
@ -1,85 +0,0 @@
|
||||
<?xml version="1.0" encoding="UTF-8"?>
|
||||
<Scheme
|
||||
LastUpgradeVersion = "1140"
|
||||
version = "1.7">
|
||||
<BuildAction
|
||||
parallelizeBuildables = "YES"
|
||||
buildImplicitDependencies = "YES">
|
||||
<BuildActionEntries>
|
||||
<BuildActionEntry
|
||||
buildForTesting = "YES"
|
||||
buildForRunning = "YES"
|
||||
buildForProfiling = "YES"
|
||||
buildForArchiving = "YES"
|
||||
buildForAnalyzing = "YES">
|
||||
<BuildableReference
|
||||
BuildableIdentifier = "primary"
|
||||
BlueprintIdentifier = "5099A06B240242BA0062B6F2"
|
||||
BuildableName = "SecretAgentKit.framework"
|
||||
BlueprintName = "SecretAgentKit"
|
||||
ReferencedContainer = "container:Secretive.xcodeproj">
|
||||
</BuildableReference>
|
||||
</BuildActionEntry>
|
||||
</BuildActionEntries>
|
||||
</BuildAction>
|
||||
<TestAction
|
||||
buildConfiguration = "Test"
|
||||
selectedDebuggerIdentifier = "Xcode.DebuggerFoundation.Debugger.LLDB"
|
||||
selectedLauncherIdentifier = "Xcode.DebuggerFoundation.Launcher.LLDB"
|
||||
shouldUseLaunchSchemeArgsEnv = "YES">
|
||||
<TestPlans>
|
||||
<TestPlanReference
|
||||
reference = "container:Config/Secretive.xctestplan"
|
||||
default = "YES">
|
||||
</TestPlanReference>
|
||||
</TestPlans>
|
||||
<Testables>
|
||||
<TestableReference
|
||||
skipped = "NO"
|
||||
parallelizable = "YES"
|
||||
testExecutionOrdering = "random">
|
||||
<BuildableReference
|
||||
BuildableIdentifier = "primary"
|
||||
BlueprintIdentifier = "5099A073240242BA0062B6F2"
|
||||
BuildableName = "SecretAgentKitTests.xctest"
|
||||
BlueprintName = "SecretAgentKitTests"
|
||||
ReferencedContainer = "container:Secretive.xcodeproj">
|
||||
</BuildableReference>
|
||||
</TestableReference>
|
||||
</Testables>
|
||||
</TestAction>
|
||||
<LaunchAction
|
||||
buildConfiguration = "Debug"
|
||||
selectedDebuggerIdentifier = "Xcode.DebuggerFoundation.Debugger.LLDB"
|
||||
selectedLauncherIdentifier = "Xcode.DebuggerFoundation.Launcher.LLDB"
|
||||
launchStyle = "0"
|
||||
useCustomWorkingDirectory = "NO"
|
||||
ignoresPersistentStateOnLaunch = "NO"
|
||||
debugDocumentVersioning = "YES"
|
||||
debugServiceExtension = "internal"
|
||||
allowLocationSimulation = "YES">
|
||||
</LaunchAction>
|
||||
<ProfileAction
|
||||
buildConfiguration = "Release"
|
||||
shouldUseLaunchSchemeArgsEnv = "YES"
|
||||
savedToolIdentifier = ""
|
||||
useCustomWorkingDirectory = "NO"
|
||||
debugDocumentVersioning = "YES">
|
||||
<MacroExpansion>
|
||||
<BuildableReference
|
||||
BuildableIdentifier = "primary"
|
||||
BlueprintIdentifier = "5099A06B240242BA0062B6F2"
|
||||
BuildableName = "SecretAgentKit.framework"
|
||||
BlueprintName = "SecretAgentKit"
|
||||
ReferencedContainer = "container:Secretive.xcodeproj">
|
||||
</BuildableReference>
|
||||
</MacroExpansion>
|
||||
</ProfileAction>
|
||||
<AnalyzeAction
|
||||
buildConfiguration = "Debug">
|
||||
</AnalyzeAction>
|
||||
<ArchiveAction
|
||||
buildConfiguration = "Release"
|
||||
revealArchiveInOrganizer = "YES">
|
||||
</ArchiveAction>
|
||||
</Scheme>
|
@ -1,71 +0,0 @@
|
||||
<?xml version="1.0" encoding="UTF-8"?>
|
||||
<Scheme
|
||||
LastUpgradeVersion = "1140"
|
||||
version = "1.7">
|
||||
<BuildAction
|
||||
parallelizeBuildables = "YES"
|
||||
buildImplicitDependencies = "YES">
|
||||
<BuildActionEntries>
|
||||
<BuildActionEntry
|
||||
buildForTesting = "YES"
|
||||
buildForRunning = "YES"
|
||||
buildForProfiling = "YES"
|
||||
buildForArchiving = "YES"
|
||||
buildForAnalyzing = "YES">
|
||||
<BuildableReference
|
||||
BuildableIdentifier = "primary"
|
||||
BlueprintIdentifier = "50617DA723FCE4AB0099B055"
|
||||
BuildableName = "SecretKit.framework"
|
||||
BlueprintName = "SecretKit"
|
||||
ReferencedContainer = "container:Secretive.xcodeproj">
|
||||
</BuildableReference>
|
||||
</BuildActionEntry>
|
||||
</BuildActionEntries>
|
||||
</BuildAction>
|
||||
<TestAction
|
||||
buildConfiguration = "Test"
|
||||
selectedDebuggerIdentifier = "Xcode.DebuggerFoundation.Debugger.LLDB"
|
||||
selectedLauncherIdentifier = "Xcode.DebuggerFoundation.Launcher.LLDB"
|
||||
shouldUseLaunchSchemeArgsEnv = "YES">
|
||||
<TestPlans>
|
||||
<TestPlanReference
|
||||
reference = "container:Config/Secretive.xctestplan"
|
||||
default = "YES">
|
||||
</TestPlanReference>
|
||||
</TestPlans>
|
||||
</TestAction>
|
||||
<LaunchAction
|
||||
buildConfiguration = "Debug"
|
||||
selectedDebuggerIdentifier = "Xcode.DebuggerFoundation.Debugger.LLDB"
|
||||
selectedLauncherIdentifier = "Xcode.DebuggerFoundation.Launcher.LLDB"
|
||||
launchStyle = "0"
|
||||
useCustomWorkingDirectory = "NO"
|
||||
ignoresPersistentStateOnLaunch = "NO"
|
||||
debugDocumentVersioning = "YES"
|
||||
debugServiceExtension = "internal"
|
||||
allowLocationSimulation = "YES">
|
||||
</LaunchAction>
|
||||
<ProfileAction
|
||||
buildConfiguration = "Release"
|
||||
shouldUseLaunchSchemeArgsEnv = "YES"
|
||||
savedToolIdentifier = ""
|
||||
useCustomWorkingDirectory = "NO"
|
||||
debugDocumentVersioning = "YES">
|
||||
<MacroExpansion>
|
||||
<BuildableReference
|
||||
BuildableIdentifier = "primary"
|
||||
BlueprintIdentifier = "50617DA723FCE4AB0099B055"
|
||||
BuildableName = "SecretKit.framework"
|
||||
BlueprintName = "SecretKit"
|
||||
ReferencedContainer = "container:Secretive.xcodeproj">
|
||||
</BuildableReference>
|
||||
</MacroExpansion>
|
||||
</ProfileAction>
|
||||
<AnalyzeAction
|
||||
buildConfiguration = "Debug">
|
||||
</AnalyzeAction>
|
||||
<ArchiveAction
|
||||
buildConfiguration = "Release"
|
||||
revealArchiveInOrganizer = "YES">
|
||||
</ArchiveAction>
|
||||
</Scheme>
|
@ -1,43 +0,0 @@
|
||||
import SwiftUI
|
||||
import SecretKit
|
||||
|
||||
struct SecretDetailView<SecretType: Secret>: View {
|
||||
|
||||
@State var secret: SecretType
|
||||
|
||||
private let keyWriter = OpenSSHKeyWriter()
|
||||
|
||||
var body: some View {
|
||||
Form {
|
||||
Section {
|
||||
CopyableView(title: "Fingerprint", image: Image(systemName: "touchid"), text: keyWriter.openSSHFingerprint(secret: secret))
|
||||
Spacer()
|
||||
.frame(height: 20)
|
||||
CopyableView(title: "Public Key", image: Image(systemName: "key"), text: keyWriter.openSSHString(secret: secret))
|
||||
Spacer()
|
||||
}
|
||||
}
|
||||
.padding()
|
||||
.frame(minHeight: 200, maxHeight: .infinity)
|
||||
}
|
||||
|
||||
var keyString: String {
|
||||
keyWriter.openSSHString(secret: secret)
|
||||
}
|
||||
|
||||
func copy() {
|
||||
NSPasteboard.general.declareTypes([.string], owner: nil)
|
||||
NSPasteboard.general.setString(keyString, forType: .string)
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
#if DEBUG
|
||||
|
||||
struct SecretDetailView_Previews: PreviewProvider {
|
||||
static var previews: some View {
|
||||
SecretDetailView(secret: Preview.Store(numberOfRandomSecrets: 1).secrets[0])
|
||||
}
|
||||
}
|
||||
|
||||
#endif
|
@ -1,41 +0,0 @@
|
||||
import SwiftUI
|
||||
import SecretKit
|
||||
|
||||
struct SecretListView: View {
|
||||
|
||||
@ObservedObject var store: AnySecretStore
|
||||
@Binding var activeSecret: AnySecret.ID?
|
||||
@Binding var deletingSecret: AnySecret?
|
||||
|
||||
var deletedSecret: (AnySecret) -> Void
|
||||
|
||||
var body: some View {
|
||||
ForEach(store.secrets) { secret in
|
||||
NavigationLink(destination: SecretDetailView(secret: secret), tag: secret.id, selection: $activeSecret) {
|
||||
Text(secret.name)
|
||||
}.contextMenu {
|
||||
if store is AnySecretStoreModifiable {
|
||||
Button(action: { delete(secret: secret) }) {
|
||||
Text("Delete")
|
||||
}
|
||||
}
|
||||
}
|
||||
.popover(isPresented: .constant(deletingSecret == secret)) {
|
||||
if let modifiable = store as? AnySecretStoreModifiable {
|
||||
DeleteSecretView(store: modifiable, secret: secret) { deleted in
|
||||
deletingSecret = nil
|
||||
if deleted {
|
||||
deletedSecret(AnySecret(secret))
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
}
|
||||
}
|
||||
|
||||
func delete<SecretType: Secret>(secret: SecretType) {
|
||||
deletingSecret = AnySecret(secret)
|
||||
}
|
||||
|
||||
}
|
@ -1,22 +0,0 @@
|
||||
<?xml version="1.0" encoding="UTF-8"?>
|
||||
<!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd">
|
||||
<plist version="1.0">
|
||||
<dict>
|
||||
<key>CFBundleDevelopmentRegion</key>
|
||||
<string>$(DEVELOPMENT_LANGUAGE)</string>
|
||||
<key>CFBundleExecutable</key>
|
||||
<string>$(EXECUTABLE_NAME)</string>
|
||||
<key>CFBundleIdentifier</key>
|
||||
<string>$(PRODUCT_BUNDLE_IDENTIFIER)</string>
|
||||
<key>CFBundleInfoDictionaryVersion</key>
|
||||
<string>6.0</string>
|
||||
<key>CFBundleName</key>
|
||||
<string>$(PRODUCT_NAME)</string>
|
||||
<key>CFBundlePackageType</key>
|
||||
<string>$(PRODUCT_BUNDLE_PACKAGE_TYPE)</string>
|
||||
<key>CFBundleShortVersionString</key>
|
||||
<string>1.0</string>
|
||||
<key>CFBundleVersion</key>
|
||||
<string>1</string>
|
||||
</dict>
|
||||
</plist>
|
26
Sources/Config/Secretive.xctestplan
Normal file
26
Sources/Config/Secretive.xctestplan
Normal file
@ -0,0 +1,26 @@
|
||||
{
|
||||
"configurations" : [
|
||||
{
|
||||
"id" : "5896AE5A-6D5A-48D3-837B-668B646A3273",
|
||||
"name" : "Configuration 1",
|
||||
"options" : {
|
||||
|
||||
}
|
||||
}
|
||||
],
|
||||
"defaultOptions" : {
|
||||
|
||||
},
|
||||
"testTargets" : [
|
||||
{
|
||||
"enabled" : false,
|
||||
"parallelizable" : true,
|
||||
"target" : {
|
||||
"containerPath" : "container:Secretive.xcodeproj",
|
||||
"identifier" : "50617D9323FCE48E0099B055",
|
||||
"name" : "SecretiveTests"
|
||||
}
|
||||
}
|
||||
],
|
||||
"version" : 1
|
||||
}
|
70
Sources/Packages/Package.swift
Normal file
70
Sources/Packages/Package.swift
Normal file
@ -0,0 +1,70 @@
|
||||
// swift-tools-version:5.5
|
||||
// The swift-tools-version declares the minimum version of Swift required to build this package.
|
||||
|
||||
import PackageDescription
|
||||
|
||||
let package = Package(
|
||||
name: "SecretivePackages",
|
||||
platforms: [
|
||||
.macOS(.v11)
|
||||
],
|
||||
products: [
|
||||
.library(
|
||||
name: "SecretKit",
|
||||
targets: ["SecretKit"]),
|
||||
.library(
|
||||
name: "SecureEnclaveSecretKit",
|
||||
targets: ["SecureEnclaveSecretKit"]),
|
||||
.library(
|
||||
name: "SmartCardSecretKit",
|
||||
targets: ["SmartCardSecretKit"]),
|
||||
.library(
|
||||
name: "SecretAgentKit",
|
||||
targets: ["SecretAgentKit"]),
|
||||
.library(
|
||||
name: "SecretAgentKitHeaders",
|
||||
targets: ["SecretAgentKitHeaders"]),
|
||||
.library(
|
||||
name: "Brief",
|
||||
targets: ["Brief"]),
|
||||
],
|
||||
dependencies: [
|
||||
],
|
||||
targets: [
|
||||
.target(
|
||||
name: "SecretKit",
|
||||
dependencies: []
|
||||
),
|
||||
.testTarget(
|
||||
name: "SecretKitTests",
|
||||
dependencies: ["SecretKit", "SecureEnclaveSecretKit", "SmartCardSecretKit"]
|
||||
),
|
||||
.target(
|
||||
name: "SecureEnclaveSecretKit",
|
||||
dependencies: ["SecretKit"]
|
||||
),
|
||||
.target(
|
||||
name: "SmartCardSecretKit",
|
||||
dependencies: ["SecretKit"]
|
||||
),
|
||||
.target(
|
||||
name: "SecretAgentKit",
|
||||
dependencies: ["SecretKit", "SecretAgentKitHeaders"]
|
||||
),
|
||||
.systemLibrary(
|
||||
name: "SecretAgentKitHeaders"
|
||||
),
|
||||
.testTarget(
|
||||
name: "SecretAgentKitTests",
|
||||
dependencies: ["SecretAgentKit"])
|
||||
,
|
||||
.target(
|
||||
name: "Brief",
|
||||
dependencies: []
|
||||
),
|
||||
.testTarget(
|
||||
name: "BriefTests",
|
||||
dependencies: ["Brief"]
|
||||
),
|
||||
]
|
||||
)
|
@ -0,0 +1,15 @@
|
||||
# ``Brief``
|
||||
|
||||
Brief is a collection of protocols and concrete implmentation describing updates.
|
||||
|
||||
## Topics
|
||||
|
||||
### Versioning
|
||||
|
||||
- ``SemVer``
|
||||
- ``Release``
|
||||
|
||||
### Updater
|
||||
|
||||
- ``UpdaterProtocol``
|
||||
- ``Updater``
|
80
Sources/Packages/Sources/Brief/Release.swift
Normal file
80
Sources/Packages/Sources/Brief/Release.swift
Normal file
@ -0,0 +1,80 @@
|
||||
import Foundation
|
||||
|
||||
/// A release is a representation of a downloadable update.
|
||||
public struct Release: Codable {
|
||||
|
||||
/// The user-facing name of the release. Typically "Secretive 1.2.3"
|
||||
public let name: String
|
||||
|
||||
/// A boolean describing whether or not the release is a prerelase build.
|
||||
public let prerelease: Bool
|
||||
|
||||
/// A URL pointing to the HTML page for the release.
|
||||
public let html_url: URL
|
||||
|
||||
/// A user-facing description of the contents of the update.
|
||||
public let body: String
|
||||
|
||||
/// Initializes a Release.
|
||||
/// - Parameters:
|
||||
/// - name: The user-facing name of the release.
|
||||
/// - prerelease: A boolean describing whether or not the release is a prerelase build.
|
||||
/// - html_url: A URL pointing to the HTML page for the release.
|
||||
/// - body: A user-facing description of the contents of the update.
|
||||
public init(name: String, prerelease: Bool, html_url: URL, body: String) {
|
||||
self.name = name
|
||||
self.prerelease = prerelease
|
||||
self.html_url = html_url
|
||||
self.body = body
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
extension Release: Identifiable {
|
||||
|
||||
public var id: String {
|
||||
html_url.absoluteString
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
extension Release: Comparable {
|
||||
|
||||
public static func < (lhs: Release, rhs: Release) -> Bool {
|
||||
lhs.version < rhs.version
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
extension Release {
|
||||
|
||||
/// A boolean describing whether or not the release contains critical security content.
|
||||
/// - Note: this is determined by the presence of the phrase "Critical Security Update" in the ``body``.
|
||||
/// - Warning: If this property is true, the user will not be able to dismiss UI or reminders associated with the update.
|
||||
public var critical: Bool {
|
||||
body.contains(Constants.securityContent)
|
||||
}
|
||||
|
||||
/// A ``SemVer`` representation of the version number of the release.
|
||||
public var version: SemVer {
|
||||
SemVer(name)
|
||||
}
|
||||
|
||||
/// The minimum macOS version required to run the update.
|
||||
public var minimumOSVersion: SemVer {
|
||||
guard let range = body.range(of: "Minimum macOS Version"),
|
||||
let numberStart = body.rangeOfCharacter(from: CharacterSet.decimalDigits, options: [], range: range.upperBound..<body.endIndex) else { return SemVer("11.0.0") }
|
||||
let numbersEnd = body.rangeOfCharacter(from: CharacterSet.whitespacesAndNewlines, options: [], range: numberStart.upperBound..<body.endIndex)?.lowerBound ?? body.endIndex
|
||||
let version = numberStart.lowerBound..<numbersEnd
|
||||
return SemVer(String(body[version]))
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
extension Release {
|
||||
|
||||
enum Constants {
|
||||
static let securityContent = "Critical Security Update"
|
||||
}
|
||||
|
||||
}
|
43
Sources/Packages/Sources/Brief/SemVer.swift
Normal file
43
Sources/Packages/Sources/Brief/SemVer.swift
Normal file
@ -0,0 +1,43 @@
|
||||
import Foundation
|
||||
|
||||
/// A representation of a Semantic Version.
|
||||
public struct SemVer {
|
||||
|
||||
/// The SemVer broken into an array of integers.
|
||||
let versionNumbers: [Int]
|
||||
|
||||
/// Initializes a SemVer from a string representation.
|
||||
/// - Parameter version: A string representation of the SemVer, formatted as "major.minor.patch".
|
||||
public init(_ version: String) {
|
||||
// Betas have the format 1.2.3_beta1
|
||||
let strippedBeta = version.split(separator: "_").first!
|
||||
var split = strippedBeta.split(separator: ".").compactMap { Int($0) }
|
||||
while split.count < 3 {
|
||||
split.append(0)
|
||||
}
|
||||
versionNumbers = split
|
||||
}
|
||||
|
||||
/// Initializes a SemVer from an `OperatingSystemVersion` representation.
|
||||
/// - Parameter version: An `OperatingSystemVersion` representation of the SemVer.
|
||||
public init(_ version: OperatingSystemVersion) {
|
||||
versionNumbers = [version.majorVersion, version.minorVersion, version.patchVersion]
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
extension SemVer: Comparable {
|
||||
|
||||
public static func < (lhs: SemVer, rhs: SemVer) -> Bool {
|
||||
for (latest, current) in zip(lhs.versionNumbers, rhs.versionNumbers) {
|
||||
if latest < current {
|
||||
return true
|
||||
} else if latest > current {
|
||||
return false
|
||||
}
|
||||
}
|
||||
return false
|
||||
}
|
||||
|
||||
|
||||
}
|
97
Sources/Packages/Sources/Brief/Updater.swift
Normal file
97
Sources/Packages/Sources/Brief/Updater.swift
Normal file
@ -0,0 +1,97 @@
|
||||
import Foundation
|
||||
import Combine
|
||||
|
||||
/// A concrete implementation of ``UpdaterProtocol`` which considers the current release and OS version.
|
||||
public class Updater: ObservableObject, UpdaterProtocol {
|
||||
|
||||
@Published public var update: Release?
|
||||
public let testBuild: Bool
|
||||
|
||||
/// The current OS version.
|
||||
private let osVersion: SemVer
|
||||
/// The current version of the app that is running.
|
||||
private let currentVersion: SemVer
|
||||
|
||||
/// Initializes an Updater.
|
||||
/// - Parameters:
|
||||
/// - checkOnLaunch: A boolean describing whether the Updater should check for available updates on launch.
|
||||
/// - checkFrequency: The interval at which the Updater should check for updates. Subject to a tolerance of 1 hour.
|
||||
/// - osVersion: The current OS version.
|
||||
/// - currentVersion: The current version of the app that is running.
|
||||
public init(checkOnLaunch: Bool, checkFrequency: TimeInterval = Measurement(value: 24, unit: UnitDuration.hours).converted(to: .seconds).value, osVersion: SemVer = SemVer(ProcessInfo.processInfo.operatingSystemVersion), currentVersion: SemVer = SemVer(Bundle.main.infoDictionary?["CFBundleShortVersionString"] as? String ?? "0.0.0")) {
|
||||
self.osVersion = osVersion
|
||||
self.currentVersion = currentVersion
|
||||
testBuild = currentVersion == SemVer("0.0.0")
|
||||
if checkOnLaunch {
|
||||
// Don't do a launch check if the user hasn't seen the setup prompt explaining updater yet.
|
||||
checkForUpdates()
|
||||
}
|
||||
let timer = Timer.scheduledTimer(withTimeInterval: checkFrequency, repeats: true) { _ in
|
||||
self.checkForUpdates()
|
||||
}
|
||||
timer.tolerance = 60*60
|
||||
}
|
||||
|
||||
/// Manually trigger an update check.
|
||||
public func checkForUpdates() {
|
||||
URLSession.shared.dataTask(with: Constants.updateURL) { data, _, _ in
|
||||
guard let data = data else { return }
|
||||
guard let releases = try? JSONDecoder().decode([Release].self, from: data) else { return }
|
||||
self.evaluate(releases: releases)
|
||||
}.resume()
|
||||
}
|
||||
|
||||
/// 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) {
|
||||
guard !release.critical else { return }
|
||||
defaults.set(true, forKey: release.name)
|
||||
DispatchQueue.main.async {
|
||||
self.update = nil
|
||||
}
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
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]) {
|
||||
guard let release = releases
|
||||
.sorted()
|
||||
.reversed()
|
||||
.filter({ !$0.prerelease })
|
||||
.first(where: { $0.minimumOSVersion <= osVersion }) else { return }
|
||||
guard !userIgnored(release: release) else { return }
|
||||
guard !release.prerelease else { return }
|
||||
let latestVersion = SemVer(release.name)
|
||||
if latestVersion > currentVersion {
|
||||
DispatchQueue.main.async {
|
||||
self.update = release
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// Checks whether the user has ignored a release.
|
||||
/// - Parameter release: The release to check.
|
||||
/// - Returns: A boolean describing whether the user has ignored the release. Will always be false if the release is critical.
|
||||
func userIgnored(release: Release) -> Bool {
|
||||
guard !release.critical else { return false }
|
||||
return defaults.bool(forKey: release.name)
|
||||
}
|
||||
|
||||
/// The user defaults used to store user ignore state.
|
||||
var defaults: UserDefaults {
|
||||
UserDefaults(suiteName: "com.maxgoedjen.Secretive.updater.ignorelist")!
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
extension Updater {
|
||||
|
||||
enum Constants {
|
||||
static let updateURL = URL(string: "https://api.github.com/repos/maxgoedjen/secretive/releases")!
|
||||
}
|
||||
|
||||
}
|
12
Sources/Packages/Sources/Brief/UpdaterProtocol.swift
Normal file
12
Sources/Packages/Sources/Brief/UpdaterProtocol.swift
Normal file
@ -0,0 +1,12 @@
|
||||
import Foundation
|
||||
|
||||
/// A protocol for retreiving the latest available version of an app.
|
||||
public protocol UpdaterProtocol: ObservableObject {
|
||||
|
||||
/// The latest update
|
||||
var update: Release? { get }
|
||||
/// A boolean describing whether or not the current build of the app is a "test" build (ie, a debug build or otherwise special build)
|
||||
var testBuild: Bool { get }
|
||||
|
||||
}
|
||||
|
@ -4,6 +4,7 @@ import OSLog
|
||||
import SecretKit
|
||||
import AppKit
|
||||
|
||||
/// The `Agent` is an implementation of an SSH agent. It manages coordination and access between a socket, traces requests, notifies witnesses and passes requests to stores.
|
||||
public class Agent {
|
||||
|
||||
private let storeList: SecretStoreList
|
||||
@ -11,6 +12,10 @@ public class Agent {
|
||||
private let writer = OpenSSHKeyWriter()
|
||||
private let requestTracer = SigningRequestTracer()
|
||||
|
||||
/// Initializes an agent with a store list and a witness.
|
||||
/// - Parameters:
|
||||
/// - storeList: The `SecretStoreList` to make available.
|
||||
/// - witness: A witness to notify of requests.
|
||||
public init(storeList: SecretStoreList, witness: SigningWitness? = nil) {
|
||||
Logger().debug("Agent is running")
|
||||
self.storeList = storeList
|
||||
@ -21,20 +26,27 @@ public class Agent {
|
||||
|
||||
extension Agent {
|
||||
|
||||
public func handle(reader: FileHandleReader, writer: FileHandleWriter) {
|
||||
/// Handles an incoming request.
|
||||
/// - Parameters:
|
||||
/// - reader: A ``FileHandleReader`` to read the content of the request.
|
||||
/// - writer: A ``FileHandleWriter`` to write the response to.
|
||||
/// - Return value:
|
||||
/// - Boolean if data could be read
|
||||
public func handle(reader: FileHandleReader, writer: FileHandleWriter) -> Bool {
|
||||
Logger().debug("Agent handling new data")
|
||||
let data = reader.availableData
|
||||
guard !data.isEmpty else { return }
|
||||
let data = Data(reader.availableData)
|
||||
guard data.count > 4 else { return false}
|
||||
let requestTypeInt = data[4]
|
||||
guard let requestType = SSHAgent.RequestType(rawValue: requestTypeInt) else {
|
||||
writer.write(OpenSSHKeyWriter().lengthAndData(of: SSHAgent.ResponseType.agentFailure.data))
|
||||
Logger().debug("Agent returned \(SSHAgent.ResponseType.agentFailure.debugDescription)")
|
||||
return
|
||||
return true
|
||||
}
|
||||
Logger().debug("Agent handling request of type \(requestType.debugDescription)")
|
||||
let subData = Data(data[5...])
|
||||
let response = handle(requestType: requestType, data: subData, reader: reader)
|
||||
writer.write(response)
|
||||
return true
|
||||
}
|
||||
|
||||
func handle(requestType: SSHAgent.RequestType, data: Data, reader: FileHandleReader) -> Data {
|
||||
@ -64,6 +76,8 @@ extension Agent {
|
||||
|
||||
extension Agent {
|
||||
|
||||
/// Lists the identities available for signing operations
|
||||
/// - Returns: An OpenSSH formatted Data payload listing the identities available for signing operations.
|
||||
func identities() -> Data {
|
||||
let secrets = storeList.stores.flatMap(\.secrets)
|
||||
var count = UInt32(secrets.count).bigEndian
|
||||
@ -80,6 +94,11 @@ extension Agent {
|
||||
return countData + keyData
|
||||
}
|
||||
|
||||
/// Notifies witnesses of a pending signature request, and performs the signing operation if none object.
|
||||
/// - Parameters:
|
||||
/// - data: The data to sign.
|
||||
/// - provenance: A ``SecretKit.SigningRequestProvenance`` object describing the origin of the request.
|
||||
/// - Returns: An OpenSSH formatted Data payload containing the signed data response.
|
||||
func sign(data: Data, provenance: SigningRequestProvenance) throws -> Data {
|
||||
let reader = OpenSSHReader(data: data)
|
||||
let hash = reader.readNextChunk()
|
||||
@ -89,11 +108,12 @@ extension Agent {
|
||||
}
|
||||
|
||||
if let witness = witness {
|
||||
try witness.speakNowOrForeverHoldYourPeace(forAccessTo: secret, by: provenance)
|
||||
try witness.speakNowOrForeverHoldYourPeace(forAccessTo: secret, from: store, by: provenance)
|
||||
}
|
||||
|
||||
let dataToSign = reader.readNextChunk()
|
||||
let derSignature = try store.sign(data: dataToSign, with: secret, for: provenance)
|
||||
let signed = try store.sign(data: dataToSign, with: secret, for: provenance)
|
||||
let derSignature = signed.data
|
||||
|
||||
let curveData = writer.curveType(for: secret.algorithm, length: secret.keySize).data(using: .utf8)!
|
||||
|
||||
@ -134,7 +154,7 @@ extension Agent {
|
||||
signedData.append(writer.lengthAndData(of: sub))
|
||||
|
||||
if let witness = witness {
|
||||
try witness.witness(accessTo: secret, by: provenance)
|
||||
try witness.witness(accessTo: secret, from: store, by: provenance, requiredAuthentication: signed.requiredAuthentication)
|
||||
}
|
||||
|
||||
Logger().debug("Agent signed request")
|
||||
@ -146,6 +166,9 @@ extension Agent {
|
||||
|
||||
extension Agent {
|
||||
|
||||
/// Finds a ``Secret`` matching a specified hash whos signature was requested.
|
||||
/// - Parameter hash: The hash to match against.
|
||||
/// - Returns: A ``Secret`` and the ``SecretStore`` containing it, if a match is found.
|
||||
func secret(matching hash: Data) -> (AnySecretStore, AnySecret)? {
|
||||
storeList.stores.compactMap { store -> (AnySecretStore, AnySecret)? in
|
||||
let allMatching = store.secrets.filter { secret in
|
||||
@ -163,6 +186,7 @@ extension Agent {
|
||||
|
||||
extension Agent {
|
||||
|
||||
/// An error involving agent operations..
|
||||
enum AgentError: Error {
|
||||
case unhandledType
|
||||
case noMatchingKey
|
@ -0,0 +1,23 @@
|
||||
# ``SecretAgentKit``
|
||||
|
||||
SecretAgentKit is a collection of types that allow SecretAgent to conform to the SSH agent protocol.
|
||||
|
||||
## Topics
|
||||
|
||||
### Agent
|
||||
|
||||
- ``Agent``
|
||||
|
||||
### Protocol
|
||||
|
||||
- ``SSHAgent``
|
||||
|
||||
### Request Notification
|
||||
|
||||
- ``SigningWitness``
|
||||
|
||||
### Socket Operations
|
||||
|
||||
- ``SocketController``
|
||||
- ``FileHandleReader``
|
||||
- ``FileHandleWriter``
|
@ -1,15 +1,21 @@
|
||||
import Foundation
|
||||
|
||||
/// Protocol abstraction of the reading aspects of FileHandle.
|
||||
public protocol FileHandleReader {
|
||||
|
||||
/// Gets data that is available for reading.
|
||||
var availableData: Data { get }
|
||||
/// A file descriptor of the handle.
|
||||
var fileDescriptor: Int32 { get }
|
||||
/// The process ID of the process coonnected to the other end of the FileHandle.
|
||||
var pidOfConnectedProcess: Int32 { get }
|
||||
|
||||
}
|
||||
|
||||
/// Protocol abstraction of the writing aspects of FileHandle.
|
||||
public protocol FileHandleWriter {
|
||||
|
||||
/// Writes data to the handle.
|
||||
func write(_ data: Data)
|
||||
|
||||
}
|
@ -1,10 +1,13 @@
|
||||
import Foundation
|
||||
|
||||
/// A namespace for the SSH Agent Protocol, as described in https://tools.ietf.org/id/draft-miller-ssh-agent-01.html
|
||||
public enum SSHAgent {}
|
||||
|
||||
extension SSHAgent {
|
||||
|
||||
/// The type of the SSH Agent Request, as described in https://tools.ietf.org/id/draft-miller-ssh-agent-01.html#rfc.section.5.1
|
||||
public enum RequestType: UInt8, CustomDebugStringConvertible {
|
||||
|
||||
case requestIdentities = 11
|
||||
case signRequest = 13
|
||||
|
||||
@ -18,7 +21,9 @@ extension SSHAgent {
|
||||
}
|
||||
}
|
||||
|
||||
/// The type of the SSH Agent Response, as described in https://tools.ietf.org/id/draft-miller-ssh-agent-01.html#rfc.section.5.1
|
||||
public enum ResponseType: UInt8, CustomDebugStringConvertible {
|
||||
|
||||
case agentFailure = 5
|
||||
case agentIdentitiesAnswer = 12
|
||||
case agentSignResponse = 14
|
@ -2,12 +2,17 @@ import Foundation
|
||||
import AppKit
|
||||
import Security
|
||||
import SecretKit
|
||||
import SecretAgentKitHeaders
|
||||
|
||||
/// An object responsible for generating ``SecretKit.SigningRequestProvenance`` objects.
|
||||
struct SigningRequestTracer {
|
||||
}
|
||||
|
||||
extension SigningRequestTracer {
|
||||
|
||||
/// Generates a ``SecretKit.SigningRequestProvenance`` from a ``FileHandleReader``.
|
||||
/// - Parameter fileHandleReader: The reader involved in processing the request.
|
||||
/// - Returns: A ``SecretKit.SigningRequestProvenance`` describing the origin of the request.
|
||||
func provenance(from fileHandleReader: FileHandleReader) -> SigningRequestProvenance {
|
||||
let firstInfo = process(from: fileHandleReader.pidOfConnectedProcess)
|
||||
|
||||
@ -18,6 +23,9 @@ extension SigningRequestTracer {
|
||||
return provenance
|
||||
}
|
||||
|
||||
/// Generates a `kinfo_proc` representation of the provided process ID.
|
||||
/// - Parameter pid: The process ID to look up.
|
||||
/// - Returns: a `kinfo_proc` struct describing the process ID.
|
||||
func pidAndNameInfo(from pid: Int32) -> kinfo_proc {
|
||||
var len = MemoryLayout<kinfo_proc>.size
|
||||
let infoPointer = UnsafeMutableRawPointer.allocate(byteCount: len, alignment: 1)
|
||||
@ -26,6 +34,9 @@ extension SigningRequestTracer {
|
||||
return infoPointer.load(as: kinfo_proc.self)
|
||||
}
|
||||
|
||||
/// Generates a ``SecretKit.SigningRequestProvenance.Process`` from a provided process ID.
|
||||
/// - Parameter pid: The process ID to look up.
|
||||
/// - Returns: A ``SecretKit.SigningRequestProvenance.Process`` describing the process.
|
||||
func process(from pid: Int32) -> SigningRequestProvenance.Process {
|
||||
var pidAndNameInfo = self.pidAndNameInfo(from: pid)
|
||||
let ppid = pidAndNameInfo.kp_eproc.e_ppid != 0 ? pidAndNameInfo.kp_eproc.e_ppid : nil
|
||||
@ -40,6 +51,9 @@ extension SigningRequestTracer {
|
||||
return SigningRequestProvenance.Process(pid: pid, processName: procName, appName: appName(for: pid), iconURL: iconURL(for: pid), path: path, validSignature: valid, parentPID: ppid)
|
||||
}
|
||||
|
||||
/// Looks up the URL for the icon of a process ID, if it has one.
|
||||
/// - Parameter pid: The process ID to look up.
|
||||
/// - Returns: A URL to the icon, if the process has one.
|
||||
func iconURL(for pid: Int32) -> URL? {
|
||||
do {
|
||||
if let app = NSRunningApplication(processIdentifier: pid), let icon = app.icon?.tiffRepresentation {
|
||||
@ -53,6 +67,9 @@ extension SigningRequestTracer {
|
||||
return nil
|
||||
}
|
||||
|
||||
/// Looks up the application name of a process ID, if it has one.
|
||||
/// - Parameter pid: The process ID to look up.
|
||||
/// - Returns: The process's display name, if the process has one.
|
||||
func appName(for pid: Int32) -> String? {
|
||||
NSRunningApplication(processIdentifier: pid)?.localizedName
|
||||
}
|
23
Sources/Packages/Sources/SecretAgentKit/SigningWitness.swift
Normal file
23
Sources/Packages/Sources/SecretAgentKit/SigningWitness.swift
Normal file
@ -0,0 +1,23 @@
|
||||
import Foundation
|
||||
import SecretKit
|
||||
|
||||
/// A protocol that allows conformers to be notified of access to secrets, and optionally prevent access.
|
||||
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:
|
||||
/// - secret: The `Secret` that will be used to sign the request.
|
||||
/// - store: The `Store` being asked to sign the request..
|
||||
/// - provenance: A `SigningRequestProvenance` object describing the origin of the request.
|
||||
/// - Note: This method being called does not imply that the requst has been authorized. If a secret requires authentication, authentication will still need to be performed by the user before the request will be performed. If the user declines or fails to authenticate, the request will fail.
|
||||
func speakNowOrForeverHoldYourPeace(forAccessTo secret: AnySecret, from store: AnySecretStore, by provenance: SigningRequestProvenance) throws
|
||||
|
||||
/// 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.
|
||||
/// - requiredAuthentication: A boolean describing whether or not authentication was required for the request.
|
||||
func witness(accessTo secret: AnySecret, from store: AnySecretStore, by provenance: SigningRequestProvenance, requiredAuthentication: Bool) throws
|
||||
|
||||
}
|
@ -1,12 +1,20 @@
|
||||
import Foundation
|
||||
import OSLog
|
||||
|
||||
/// A controller that manages socket configuration and request dispatching.
|
||||
public class SocketController {
|
||||
|
||||
/// The active FileHandle.
|
||||
private var fileHandle: FileHandle?
|
||||
/// The active SocketPort.
|
||||
private var port: SocketPort?
|
||||
public var handler: ((FileHandleReader, FileHandleWriter) -> Void)?
|
||||
/// A handler that will be notified when a new read/write handle is available.
|
||||
/// False if no data could be read
|
||||
public var handler: ((FileHandleReader, FileHandleWriter) -> Bool)?
|
||||
|
||||
|
||||
/// Initializes a socket controller with a specified path.
|
||||
/// - Parameter path: The path to use as a socket.
|
||||
public init(path: String) {
|
||||
Logger().debug("Socket controller setting up at \(path)")
|
||||
if let _ = try? FileManager.default.removeItem(atPath: path) {
|
||||
@ -20,6 +28,8 @@ public class SocketController {
|
||||
Logger().debug("Socket listening at \(path)")
|
||||
}
|
||||
|
||||
/// Configures the socket and a corresponding FileHandle.
|
||||
/// - Parameter path: The path to use as a socket.
|
||||
func configureSocket(at path: String) {
|
||||
guard let port = port else { return }
|
||||
fileHandle = FileHandle(fileDescriptor: port.socket, closeOnDealloc: true)
|
||||
@ -28,6 +38,9 @@ public class SocketController {
|
||||
fileHandle?.acceptConnectionInBackgroundAndNotify(forModes: [RunLoop.current.currentMode!])
|
||||
}
|
||||
|
||||
/// Creates a SocketPort for a path.
|
||||
/// - Parameter path: The path to use as a socket.
|
||||
/// - Returns: A configured SocketPort.
|
||||
func socketPort(at path: String) -> SocketPort {
|
||||
var addr = sockaddr_un()
|
||||
addr.sun_family = sa_family_t(AF_UNIX)
|
||||
@ -49,19 +62,28 @@ public class SocketController {
|
||||
return SocketPort(protocolFamily: AF_UNIX, socketType: SOCK_STREAM, protocol: 0, address: data)!
|
||||
}
|
||||
|
||||
/// Handles a new connection being accepted, invokes the handler, and prepares to accept new connections.
|
||||
/// - Parameter notification: A `Notification` that triggered the call.
|
||||
@objc func handleConnectionAccept(notification: Notification) {
|
||||
Logger().debug("Socket controller accepted connection")
|
||||
guard let new = notification.userInfo?[NSFileHandleNotificationFileHandleItem] as? FileHandle else { return }
|
||||
handler?(new, new)
|
||||
_ = handler?(new, new)
|
||||
new.waitForDataInBackgroundAndNotify()
|
||||
fileHandle?.acceptConnectionInBackgroundAndNotify(forModes: [RunLoop.current.currentMode!])
|
||||
}
|
||||
|
||||
/// Handles a new connection providing data and invokes the handler callback.
|
||||
/// - Parameter notification: A `Notification` that triggered the call.
|
||||
@objc func handleConnectionDataAvailable(notification: Notification) {
|
||||
Logger().debug("Socket controller has new data available")
|
||||
guard let new = notification.object as? FileHandle else { return }
|
||||
Logger().debug("Socket controller received new file handle")
|
||||
handler?(new, new)
|
||||
if((handler?(new, new)) == true) {
|
||||
Logger().debug("Socket controller handled data, wait for more data")
|
||||
new.waitForDataInBackgroundAndNotify()
|
||||
} else {
|
||||
Logger().debug("Socket controller called with empty data, socked closed")
|
||||
}
|
||||
}
|
||||
|
||||
}
|
@ -0,0 +1 @@
|
||||
|
@ -0,0 +1,4 @@
|
||||
module SecretAgentKitHeaders [system] {
|
||||
header "include/SecretAgentKit.h"
|
||||
export *
|
||||
}
|
@ -0,0 +1,31 @@
|
||||
# ``SecretKit``
|
||||
|
||||
SecretKit is a collection of protocols describing secrets and stores.
|
||||
|
||||
## Topics
|
||||
|
||||
### Base Protocols
|
||||
|
||||
- ``Secret``
|
||||
- ``SecretStore``
|
||||
- ``SecretStoreModifiable``
|
||||
|
||||
### Store List
|
||||
|
||||
- ``SecretStoreList``
|
||||
|
||||
### Type Erasers
|
||||
|
||||
- ``AnySecret``
|
||||
- ``AnySecretStore``
|
||||
- ``AnySecretStoreModifiable``
|
||||
|
||||
### OpenSSH
|
||||
|
||||
- ``OpenSSHKeyWriter``
|
||||
- ``OpenSSHReader``
|
||||
|
||||
### Signing Process
|
||||
|
||||
- ``SignedData``
|
||||
- ``SigningRequestProvenance``
|
@ -1,5 +1,6 @@
|
||||
import Foundation
|
||||
|
||||
/// Type eraser for Secret.
|
||||
public struct AnySecret: Secret {
|
||||
|
||||
let base: Any
|
@ -1,6 +1,7 @@
|
||||
import Foundation
|
||||
import Combine
|
||||
|
||||
/// Type eraser for SecretStore.
|
||||
public class AnySecretStore: SecretStore {
|
||||
|
||||
let base: Any
|
||||
@ -8,7 +9,9 @@ public class AnySecretStore: SecretStore {
|
||||
private let _id: () -> UUID
|
||||
private let _name: () -> String
|
||||
private let _secrets: () -> [AnySecret]
|
||||
private let _sign: (Data, AnySecret, SigningRequestProvenance) throws -> Data
|
||||
private let _sign: (Data, AnySecret, SigningRequestProvenance) throws -> SignedData
|
||||
private let _persistAuthentication: (AnySecret, TimeInterval) throws -> Void
|
||||
|
||||
private var sink: AnyCancellable?
|
||||
|
||||
public init<SecretStoreType>(_ secretStore: SecretStoreType) where SecretStoreType: SecretStore {
|
||||
@ -18,6 +21,7 @@ public class AnySecretStore: SecretStore {
|
||||
_id = { secretStore.id }
|
||||
_secrets = { secretStore.secrets.map { AnySecret($0) } }
|
||||
_sign = { try secretStore.sign(data: $0, with: $1.base as! SecretStoreType.SecretType, for: $2) }
|
||||
_persistAuthentication = { try secretStore.persistAuthentication(secret: $0.base as! SecretStoreType.SecretType, forDuration: $1) }
|
||||
sink = secretStore.objectWillChange.sink { _ in
|
||||
self.objectWillChange.send()
|
||||
}
|
||||
@ -39,20 +43,26 @@ public class AnySecretStore: SecretStore {
|
||||
return _secrets()
|
||||
}
|
||||
|
||||
public func sign(data: Data, with secret: AnySecret, for provenance: SigningRequestProvenance) throws -> Data {
|
||||
public func sign(data: Data, with secret: AnySecret, for provenance: SigningRequestProvenance) throws -> SignedData {
|
||||
try _sign(data, secret, provenance)
|
||||
}
|
||||
|
||||
public func persistAuthentication(secret: AnySecret, forDuration duration: TimeInterval) throws {
|
||||
try _persistAuthentication(secret, duration)
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
public class AnySecretStoreModifiable: AnySecretStore, SecretStoreModifiable {
|
||||
|
||||
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 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)
|
||||
}
|
||||
|
||||
@ -64,4 +74,8 @@ public class AnySecretStoreModifiable: AnySecretStore, SecretStoreModifiable {
|
||||
try _delete(secret)
|
||||
}
|
||||
|
||||
public func update(secret: AnySecret, name: String) throws {
|
||||
try _update(secret, name)
|
||||
}
|
||||
|
||||
}
|
@ -0,0 +1,82 @@
|
||||
import Foundation
|
||||
import CryptoKit
|
||||
|
||||
/// Generates OpenSSH representations of Secrets.
|
||||
public struct OpenSSHKeyWriter {
|
||||
|
||||
/// Initializes the writer.
|
||||
public init() {
|
||||
}
|
||||
|
||||
/// Generates an OpenSSH data payload identifying the secret.
|
||||
/// - Returns: OpenSSH data payload identifying the secret.
|
||||
public func data<SecretType: Secret>(secret: SecretType) -> Data {
|
||||
lengthAndData(of: curveType(for: secret.algorithm, length: secret.keySize).data(using: .utf8)!) +
|
||||
lengthAndData(of: curveIdentifier(for: secret.algorithm, length: secret.keySize).data(using: .utf8)!) +
|
||||
lengthAndData(of: secret.publicKey)
|
||||
}
|
||||
|
||||
/// Generates an OpenSSH string representation of the secret.
|
||||
/// - Returns: OpenSSH string representation of the secret.
|
||||
public func openSSHString<SecretType: Secret>(secret: SecretType, comment: String? = nil) -> String {
|
||||
[curveType(for: secret.algorithm, length: secret.keySize), data(secret: secret).base64EncodedString(), comment]
|
||||
.compactMap { $0 }
|
||||
.joined(separator: " ")
|
||||
}
|
||||
|
||||
/// Generates an OpenSSH SHA256 fingerprint string.
|
||||
/// - Returns: OpenSSH SHA256 fingerprint string.
|
||||
public func openSSHSHA256Fingerprint<SecretType: Secret>(secret: SecretType) -> String {
|
||||
// OpenSSL format seems to strip the padding at the end.
|
||||
let base64 = Data(SHA256.hash(data: data(secret: secret))).base64EncodedString()
|
||||
let paddingRange = base64.index(base64.endIndex, offsetBy: -2)..<base64.endIndex
|
||||
let cleaned = base64.replacingOccurrences(of: "=", with: "", range: paddingRange)
|
||||
return "SHA256:\(cleaned)"
|
||||
}
|
||||
|
||||
/// Generates an OpenSSH MD5 fingerprint string.
|
||||
/// - Returns: OpenSSH MD5 fingerprint string.
|
||||
public func openSSHMD5Fingerprint<SecretType: Secret>(secret: SecretType) -> String {
|
||||
Insecure.MD5.hash(data: data(secret: secret))
|
||||
.compactMap { ("0" + String($0, radix: 16, uppercase: false)).suffix(2) }
|
||||
.joined(separator: ":")
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
extension OpenSSHKeyWriter {
|
||||
|
||||
/// Creates an OpenSSH protocol style data object, which has a length header, followed by the data payload.
|
||||
/// - Parameter data: The data payload.
|
||||
/// - Returns: OpenSSH data.
|
||||
public func lengthAndData(of data: Data) -> Data {
|
||||
let rawLength = UInt32(data.count)
|
||||
var endian = rawLength.bigEndian
|
||||
return Data(bytes: &endian, count: UInt32.bitWidth/8) + data
|
||||
}
|
||||
|
||||
/// The fully qualified OpenSSH identifier for the algorithm.
|
||||
/// - Parameters:
|
||||
/// - algorithm: The algorithm to identify.
|
||||
/// - length: The key length of the algorithm.
|
||||
/// - Returns: The OpenSSH identifier for the algorithm.
|
||||
public func curveType(for algorithm: Algorithm, length: Int) -> String {
|
||||
switch algorithm {
|
||||
case .ellipticCurve:
|
||||
return "ecdsa-sha2-nistp" + String(describing: length)
|
||||
}
|
||||
}
|
||||
|
||||
/// The OpenSSH identifier for an algorithm.
|
||||
/// - Parameters:
|
||||
/// - algorithm: The algorithm to identify.
|
||||
/// - length: The key length of the algorithm.
|
||||
/// - Returns: The OpenSSH identifier for the algorithm.
|
||||
private func curveIdentifier(for algorithm: Algorithm, length: Int) -> String {
|
||||
switch algorithm {
|
||||
case .ellipticCurve:
|
||||
return "nistp" + String(describing: length)
|
||||
}
|
||||
}
|
||||
|
||||
}
|
@ -1,13 +1,18 @@
|
||||
import Foundation
|
||||
|
||||
/// Reads OpenSSH protocol data.
|
||||
public class OpenSSHReader {
|
||||
|
||||
var remaining: Data
|
||||
|
||||
/// Initialize the reader with an OpenSSH data payload.
|
||||
/// - Parameter data: The data to read.
|
||||
public init(data: Data) {
|
||||
remaining = Data(data)
|
||||
}
|
||||
|
||||
/// Reads the next chunk of data from the playload.
|
||||
/// - Returns: The next chunk of data.
|
||||
public func readNextChunk() -> Data {
|
||||
let lengthRange = 0..<(UInt32.bitWidth/8)
|
||||
let lengthChunk = remaining[lengthRange]
|
@ -0,0 +1,42 @@
|
||||
import Foundation
|
||||
import OSLog
|
||||
|
||||
/// Controller responsible for writing public keys to disk, so that they're easily accessible by scripts.
|
||||
public class PublicKeyFileStoreController {
|
||||
|
||||
private let logger = Logger()
|
||||
private let directory: String
|
||||
private let keyWriter = OpenSSHKeyWriter()
|
||||
|
||||
/// Initializes a PublicKeyFileStoreController.
|
||||
public init(homeDirectory: String) {
|
||||
directory = homeDirectory.appending("/PublicKeys")
|
||||
}
|
||||
|
||||
/// Writes out the keys specified to disk.
|
||||
/// - Parameter secrets: The Secrets to generate keys for.
|
||||
/// - Parameter clear: Whether or not the directory should be erased before writing keys.
|
||||
public func generatePublicKeys(for secrets: [AnySecret], clear: Bool = false) throws {
|
||||
logger.log("Writing public keys to disk")
|
||||
if clear {
|
||||
try? FileManager.default.removeItem(at: URL(fileURLWithPath: directory))
|
||||
}
|
||||
try? FileManager.default.createDirectory(at: URL(fileURLWithPath: directory), withIntermediateDirectories: false, attributes: nil)
|
||||
for secret in secrets {
|
||||
let path = path(for: secret)
|
||||
guard let data = keyWriter.openSSHString(secret: secret).data(using: .utf8) else { continue }
|
||||
FileManager.default.createFile(atPath: path, contents: data, attributes: nil)
|
||||
}
|
||||
logger.log("Finished writing public keys")
|
||||
}
|
||||
|
||||
/// The path for a Secret's public key.
|
||||
/// - Parameter secret: The Secret to return the path for.
|
||||
/// - Returns: The path to the Secret's public key.
|
||||
/// - Warning: This method returning a path does not imply that a key has been written to disk already. This method only describes where it will be written to.
|
||||
public func path<SecretType: Secret>(for secret: SecretType) -> String {
|
||||
let minimalHex = keyWriter.openSSHMD5Fingerprint(secret: secret).replacingOccurrences(of: ":", with: "")
|
||||
return directory.appending("/").appending("\(minimalHex).pub")
|
||||
}
|
||||
|
||||
}
|
@ -1,25 +1,32 @@
|
||||
import Foundation
|
||||
import Combine
|
||||
|
||||
/// A "Store Store," which holds a list of type-erased stores.
|
||||
public class SecretStoreList: ObservableObject {
|
||||
|
||||
/// The Stores managed by the SecretStoreList.
|
||||
@Published public var stores: [AnySecretStore] = []
|
||||
/// A modifiable store, if one is available.
|
||||
@Published public var modifiableStore: AnySecretStoreModifiable?
|
||||
private var sinks: [AnyCancellable] = []
|
||||
|
||||
/// Initializes a SecretStoreList.
|
||||
public init() {
|
||||
}
|
||||
|
||||
/// Adds a non-type-erased SecretStore to the list.
|
||||
public func add<SecretStoreType: SecretStore>(store: SecretStoreType) {
|
||||
addInternal(store: AnySecretStore(store))
|
||||
}
|
||||
|
||||
/// Adds a non-type-erased modifiable SecretStore.
|
||||
public func add<SecretStoreType: SecretStoreModifiable>(store: SecretStoreType) {
|
||||
let modifiable = AnySecretStoreModifiable(modifiable: store)
|
||||
modifiableStore = modifiable
|
||||
addInternal(store: modifiable)
|
||||
}
|
||||
|
||||
/// A boolean describing whether there are any Stores available.
|
||||
public var anyAvailable: Bool {
|
||||
stores.reduce(false, { $0 || $1.isAvailable })
|
||||
}
|
@ -1,14 +1,26 @@
|
||||
import Foundation
|
||||
|
||||
/// The base protocol for describing a Secret
|
||||
public protocol Secret: Identifiable, Hashable {
|
||||
|
||||
/// A user-facing string identifying the Secret.
|
||||
var name: String { get }
|
||||
/// The algorithm this secret uses.
|
||||
var algorithm: Algorithm { get }
|
||||
/// The key size for the secret.
|
||||
var keySize: Int { get }
|
||||
/// The public key data for the secret.
|
||||
var publicKey: Data { get }
|
||||
|
||||
}
|
||||
|
||||
/// The type of algorithm the Secret uses. Currently, only elliptic curve algorithms are supported.
|
||||
public enum Algorithm: Hashable {
|
||||
|
||||
case ellipticCurve
|
||||
|
||||
/// Initializes the Algorithm with a secAttr representation of an algorithm.
|
||||
/// - Parameter secAttr: the secAttr, represented as an NSNumber.
|
||||
public init(secAttr: NSNumber) {
|
||||
let secAttrString = secAttr.stringValue as CFString
|
||||
switch secAttrString {
|
64
Sources/Packages/Sources/SecretKit/Types/SecretStore.swift
Normal file
64
Sources/Packages/Sources/SecretKit/Types/SecretStore.swift
Normal file
@ -0,0 +1,64 @@
|
||||
import Foundation
|
||||
import Combine
|
||||
|
||||
/// Manages access to Secrets, and performs signature operations on data using those Secrets.
|
||||
public protocol SecretStore: ObservableObject, Identifiable {
|
||||
|
||||
associatedtype SecretType: Secret
|
||||
|
||||
/// A boolean indicating whether or not the store is available.
|
||||
var isAvailable: Bool { get }
|
||||
/// A unique identifier for the store.
|
||||
var id: UUID { get }
|
||||
/// A user-facing name for the store.
|
||||
var name: String { get }
|
||||
/// The secrets the store manages.
|
||||
var secrets: [SecretType] { get }
|
||||
|
||||
/// Signs a data payload with a specified Secret.
|
||||
/// - Parameters:
|
||||
/// - data: The data to sign.
|
||||
/// - secret: The ``Secret`` to sign with.
|
||||
/// - provenance: A ``SigningRequestProvenance`` describing where the request came from.
|
||||
/// - Returns: A ``SignedData`` object, containing the signature and metadata about the signature process.
|
||||
func sign(data: Data, with secret: SecretType, for provenance: SigningRequestProvenance) throws -> SignedData
|
||||
|
||||
/// Persists user authorization for access to a secret.
|
||||
/// - Parameters:
|
||||
/// - secret: The ``Secret`` to persist the authorization for.
|
||||
/// - duration: The duration that the authorization should persist for.
|
||||
/// - Note: This is used for temporarily unlocking access to a secret which would otherwise require authentication every single use. This is useful for situations where the user anticipates several rapid accesses to a authorization-guarded secret.
|
||||
func persistAuthentication(secret: SecretType, forDuration duration: TimeInterval) throws
|
||||
|
||||
}
|
||||
|
||||
/// A SecretStore that the Secretive admin app can modify.
|
||||
public protocol SecretStoreModifiable: SecretStore {
|
||||
|
||||
/// Creates a new ``Secret`` in the store.
|
||||
/// - Parameters:
|
||||
/// - name: The user-facing name for the ``Secret``.
|
||||
/// - requiresAuthentication: A boolean indicating whether or not the user will be required to authenticate before performing signature operations with the secret.
|
||||
func create(name: String, requiresAuthentication: Bool) throws
|
||||
|
||||
/// Deletes a Secret in the store.
|
||||
/// - Parameters:
|
||||
/// - secret: The ``Secret`` to delete.
|
||||
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) throws
|
||||
|
||||
}
|
||||
|
||||
extension NSNotification.Name {
|
||||
|
||||
// Distributed notification that keys were modified out of process (ie, that the management tool added/removed secrets)
|
||||
public static let secretStoreUpdated = NSNotification.Name("com.maxgoedjen.Secretive.secretStore.updated")
|
||||
// Internal notification that keys were reloaded from the backing store.
|
||||
public static let secretStoreReloaded = NSNotification.Name("com.maxgoedjen.Secretive.secretStore.reloaded")
|
||||
|
||||
}
|
20
Sources/Packages/Sources/SecretKit/Types/SignedData.swift
Normal file
20
Sources/Packages/Sources/SecretKit/Types/SignedData.swift
Normal file
@ -0,0 +1,20 @@
|
||||
import Foundation
|
||||
|
||||
/// Describes the output of a sign request.
|
||||
public struct SignedData {
|
||||
|
||||
/// The signed data.
|
||||
public let data: Data
|
||||
/// A boolean describing whether authentication was required during the signature process.
|
||||
public let requiredAuthentication: Bool
|
||||
|
||||
/// Initializes a new SignedData.
|
||||
/// - Parameters:
|
||||
/// - data: The signed data.
|
||||
/// - requiredAuthentication: A boolean describing whether authentication was required during the signature process.
|
||||
public init(data: Data, requiredAuthentication: Bool) {
|
||||
self.data = data
|
||||
self.requiredAuthentication = requiredAuthentication
|
||||
}
|
||||
|
||||
}
|
@ -0,0 +1,76 @@
|
||||
import Foundation
|
||||
import AppKit
|
||||
|
||||
/// Describes the chain of applications that requested a signature operation.
|
||||
public struct SigningRequestProvenance: Equatable {
|
||||
|
||||
/// A list of processes involved in the request.
|
||||
/// - Note: A chain will typically consist of many elements even for a simple request. For example, running `git fetch` in Terminal.app would generate a request chain of `ssh` -> `git` -> `zsh` -> `login` -> `Terminal.app`
|
||||
public var chain: [Process]
|
||||
public init(root: Process) {
|
||||
self.chain = [root]
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
extension SigningRequestProvenance {
|
||||
|
||||
/// The `Process` which initiated the signing request.
|
||||
public var origin: Process {
|
||||
chain.last!
|
||||
}
|
||||
|
||||
/// A boolean describing whether all processes in the request chain had a valid code signature.
|
||||
public var intact: Bool {
|
||||
chain.allSatisfy { $0.validSignature }
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
extension SigningRequestProvenance {
|
||||
|
||||
/// Describes a process in a `SigningRequestProvenance` chain.
|
||||
public struct Process: Equatable {
|
||||
|
||||
/// The pid of the process.
|
||||
public let pid: Int32
|
||||
/// A user-facing name for the process.
|
||||
public let processName: String
|
||||
/// A user-facing name for the application, if one exists.
|
||||
public let appName: String?
|
||||
/// An icon representation of the application, if one exists.
|
||||
public let iconURL: URL?
|
||||
/// The path the process exists at.
|
||||
public let path: String
|
||||
/// A boolean describing whether or not the process has a valid code signature.
|
||||
public let validSignature: Bool
|
||||
/// The pid of the process's parent.
|
||||
public let parentPID: Int32?
|
||||
|
||||
/// Initializes a Process.
|
||||
/// - Parameters:
|
||||
/// - pid: The pid of the process.
|
||||
/// - processName: A user-facing name for the process.
|
||||
/// - appName: A user-facing name for the application, if one exists.
|
||||
/// - iconURL: An icon representation of the application, if one exists.
|
||||
/// - path: The path the process exists at.
|
||||
/// - validSignature: A boolean describing whether or not the process has a valid code signature.
|
||||
/// - parentPID: The pid of the process's parent.
|
||||
public init(pid: Int32, processName: String, appName: String?, iconURL: URL?, path: String, validSignature: Bool, parentPID: Int32?) {
|
||||
self.pid = pid
|
||||
self.processName = processName
|
||||
self.appName = appName
|
||||
self.iconURL = iconURL
|
||||
self.path = path
|
||||
self.validSignature = validSignature
|
||||
self.parentPID = parentPID
|
||||
}
|
||||
|
||||
/// The best user-facing name to display for the process.
|
||||
public var displayName: String {
|
||||
appName ?? processName
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
}
|
@ -0,0 +1,3 @@
|
||||
# ``SecureEnclaveSecretKit``
|
||||
|
||||
SecureEnclaveSecretKit contains implementations of SecretKit protocols backed by the Secure Enclave.
|
@ -0,0 +1,14 @@
|
||||
# ``SecureEnclaveSecretKit/SecureEnclave``
|
||||
|
||||
## Topics
|
||||
|
||||
### Implementations
|
||||
|
||||
- ``Secret``
|
||||
- ``Store``
|
||||
|
||||
### Errors
|
||||
|
||||
- ``KeychainError``
|
||||
- ``SigningError``
|
||||
- ``SecurityError``
|
@ -0,0 +1,2 @@
|
||||
/// Namespace for the Secure Enclave implementations.
|
||||
public enum SecureEnclave {}
|
@ -1,8 +1,10 @@
|
||||
import Foundation
|
||||
import Combine
|
||||
import SecretKit
|
||||
|
||||
extension SecureEnclave {
|
||||
|
||||
/// An implementation of Secret backed by the Secure Enclave.
|
||||
public struct Secret: SecretKit.Secret {
|
||||
|
||||
public let id: Data
|
@ -2,9 +2,11 @@ import Foundation
|
||||
import Security
|
||||
import CryptoTokenKit
|
||||
import LocalAuthentication
|
||||
import SecretKit
|
||||
|
||||
extension SecureEnclave {
|
||||
|
||||
/// An implementation of Store backed by the Secure Enclave.
|
||||
public class Store: SecretStoreModifiable {
|
||||
|
||||
public var isAvailable: Bool {
|
||||
@ -17,9 +19,12 @@ extension SecureEnclave {
|
||||
public let name = NSLocalizedString("Secure Enclave", comment: "Secure Enclave")
|
||||
@Published public private(set) var secrets: [Secret] = []
|
||||
|
||||
private var persistedAuthenticationContexts: [Secret: PersistentAuthenticationContext] = [:]
|
||||
|
||||
/// Initializes a Store.
|
||||
public init() {
|
||||
DistributedNotificationCenter.default().addObserver(forName: .secretStoreUpdated, object: nil, queue: .main) { _ in
|
||||
self.reloadSecrets(notify: false)
|
||||
self.reloadSecrets(notifyAgent: false)
|
||||
}
|
||||
loadSecrets()
|
||||
}
|
||||
@ -54,13 +59,15 @@ extension SecureEnclave {
|
||||
]
|
||||
] as CFDictionary
|
||||
|
||||
var privateKey: SecKey? = nil
|
||||
var publicKey: SecKey? = nil
|
||||
let status = SecKeyGeneratePair(attributes, &publicKey, &privateKey)
|
||||
guard privateKey != nil, let pk = publicKey else {
|
||||
throw KeychainError(statusCode: status)
|
||||
var createKeyError: SecurityError?
|
||||
let keypair = SecKeyCreateRandomKey(attributes, &createKeyError)
|
||||
if let error = createKeyError {
|
||||
throw error.takeRetainedValue() as Error
|
||||
}
|
||||
try savePublicKey(pk, name: name)
|
||||
guard let keypair = keypair, let publicKey = SecKeyCopyPublicKey(keypair) else {
|
||||
throw KeychainError(statusCode: nil)
|
||||
}
|
||||
try savePublicKey(publicKey, name: name)
|
||||
reloadSecrets()
|
||||
}
|
||||
|
||||
@ -68,7 +75,7 @@ extension SecureEnclave {
|
||||
let deleteAttributes = [
|
||||
kSecClass: kSecClassKey,
|
||||
kSecAttrApplicationLabel: secret.id as CFData
|
||||
] as CFDictionary
|
||||
] as CFDictionary
|
||||
let status = SecItemDelete(deleteAttributes)
|
||||
if status != errSecSuccess {
|
||||
throw KeychainError(statusCode: status)
|
||||
@ -76,10 +83,33 @@ extension SecureEnclave {
|
||||
reloadSecrets()
|
||||
}
|
||||
|
||||
public func sign(data: Data, with secret: SecretType, for provenance: SigningRequestProvenance) throws -> Data {
|
||||
let context = LAContext()
|
||||
public func update(secret: Secret, name: String) throws {
|
||||
let updateQuery = [
|
||||
kSecClass: kSecClassKey,
|
||||
kSecAttrApplicationLabel: secret.id as CFData
|
||||
] as CFDictionary
|
||||
|
||||
let updatedAttributes = [
|
||||
kSecAttrLabel: name,
|
||||
] as CFDictionary
|
||||
|
||||
let status = SecItemUpdate(updateQuery, updatedAttributes)
|
||||
if status != errSecSuccess {
|
||||
throw KeychainError(statusCode: status)
|
||||
}
|
||||
reloadSecrets()
|
||||
}
|
||||
|
||||
public func sign(data: Data, with secret: SecretType, for provenance: SigningRequestProvenance) throws -> SignedData {
|
||||
let context: LAContext
|
||||
if let existing = persistedAuthenticationContexts[secret], existing.valid {
|
||||
context = existing.context
|
||||
} else {
|
||||
let newContext = LAContext()
|
||||
newContext.localizedCancelTitle = "Deny"
|
||||
context = newContext
|
||||
}
|
||||
context.localizedReason = "sign a request from \"\(provenance.origin.displayName)\" using secret \"\(secret.name)\""
|
||||
context.localizedCancelTitle = "Deny"
|
||||
let attributes = [
|
||||
kSecClass: kSecClassKey,
|
||||
kSecAttrKeyClass: kSecAttrKeyClassPrivate,
|
||||
@ -100,10 +130,38 @@ extension SecureEnclave {
|
||||
}
|
||||
let key = untypedSafe as! SecKey
|
||||
var signError: SecurityError?
|
||||
|
||||
let signingStartTime = Date()
|
||||
guard let signature = SecKeyCreateSignature(key, .ecdsaSignatureMessageX962SHA256, data as CFData, &signError) else {
|
||||
throw SigningError(error: signError)
|
||||
}
|
||||
return signature as Data
|
||||
let signatureDuration = Date().timeIntervalSince(signingStartTime)
|
||||
// Hack to determine if the user had to authenticate to sign.
|
||||
// Since there's now way to inspect SecAccessControl to determine (afaict).
|
||||
let requiredAuthentication = signatureDuration > Constants.unauthenticatedThreshold
|
||||
|
||||
return SignedData(data: signature as Data, requiredAuthentication: requiredAuthentication)
|
||||
}
|
||||
|
||||
public func persistAuthentication(secret: Secret, forDuration duration: TimeInterval) throws {
|
||||
let newContext = LAContext()
|
||||
newContext.touchIDAuthenticationAllowableReuseDuration = duration
|
||||
newContext.localizedCancelTitle = "Deny"
|
||||
|
||||
let formatter = DateComponentsFormatter()
|
||||
formatter.unitsStyle = .spellOut
|
||||
formatter.allowedUnits = [.hour, .minute, .day]
|
||||
|
||||
if let durationString = formatter.string(from: duration) {
|
||||
newContext.localizedReason = "unlock secret \"\(secret.name)\" for \(durationString)"
|
||||
} else {
|
||||
newContext.localizedReason = "unlock secret \"\(secret.name)\""
|
||||
}
|
||||
newContext.evaluatePolicy(LAPolicy.deviceOwnerAuthentication, localizedReason: newContext.localizedReason) { [weak self] success, _ in
|
||||
guard success else { return }
|
||||
let context = PersistentAuthenticationContext(secret: secret, context: newContext, duration: duration)
|
||||
self?.persistedAuthenticationContexts[secret] = context
|
||||
}
|
||||
}
|
||||
|
||||
}
|
||||
@ -112,14 +170,18 @@ extension SecureEnclave {
|
||||
|
||||
extension SecureEnclave.Store {
|
||||
|
||||
private func reloadSecrets(notify: Bool = true) {
|
||||
/// Reloads all secrets from the store.
|
||||
/// - Parameter notifyAgent: A boolean indicating whether a distributed notification should be posted, notifying other processes (ie, the SecretAgent) to reload their stores as well.
|
||||
private func reloadSecrets(notifyAgent: Bool = true) {
|
||||
secrets.removeAll()
|
||||
loadSecrets()
|
||||
if notify {
|
||||
DistributedNotificationCenter.default().post(name: .secretStoreUpdated, object: nil)
|
||||
NotificationCenter.default.post(name: .secretStoreReloaded, object: self)
|
||||
if notifyAgent {
|
||||
DistributedNotificationCenter.default().postNotificationName(.secretStoreUpdated, object: nil, deliverImmediately: true)
|
||||
}
|
||||
}
|
||||
|
||||
/// Loads all secrets from the store.
|
||||
private func loadSecrets() {
|
||||
let attributes = [
|
||||
kSecClass: kSecClassKey,
|
||||
@ -144,6 +206,10 @@ extension SecureEnclave.Store {
|
||||
secrets.append(contentsOf: wrapped)
|
||||
}
|
||||
|
||||
/// Saves a public key.
|
||||
/// - Parameters:
|
||||
/// - publicKey: The public key to save.
|
||||
/// - name: A user-facing name for the key.
|
||||
private func savePublicKey(_ publicKey: SecKey, name: String) throws {
|
||||
let attributes = [
|
||||
kSecClass: kSecClassKey,
|
||||
@ -160,15 +226,20 @@ extension SecureEnclave.Store {
|
||||
throw SecureEnclave.KeychainError(statusCode: status)
|
||||
}
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
extension SecureEnclave {
|
||||
|
||||
/// A wrapper around an error code reported by a Keychain API.
|
||||
public struct KeychainError: Error {
|
||||
public let statusCode: OSStatus
|
||||
/// The status code involved, if one was reported.
|
||||
public let statusCode: OSStatus?
|
||||
}
|
||||
|
||||
/// A signing-related error.
|
||||
public struct SigningError: Error {
|
||||
/// The underlying error reported by the API, if one was returned.
|
||||
public let error: SecurityError?
|
||||
}
|
||||
|
||||
@ -185,6 +256,40 @@ extension SecureEnclave {
|
||||
enum Constants {
|
||||
static let keyTag = "com.maxgoedjen.secretive.secureenclave.key".data(using: .utf8)! as CFData
|
||||
static let keyType = kSecAttrKeyTypeECSECPrimeRandom
|
||||
static let unauthenticatedThreshold: TimeInterval = 0.05
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
extension SecureEnclave {
|
||||
|
||||
/// A context describing a persisted authentication.
|
||||
private struct PersistentAuthenticationContext {
|
||||
|
||||
/// The Secret to persist authentication for.
|
||||
let secret: Secret
|
||||
/// The LAContext used to authorize the persistent context.
|
||||
let context: LAContext
|
||||
/// An expiration date for the context.
|
||||
/// - Note - Monotonic time instead of Date() to prevent people setting the clock back.
|
||||
let expiration: UInt64
|
||||
|
||||
/// Initializes a context.
|
||||
/// - Parameters:
|
||||
/// - secret: The Secret to persist authentication for.
|
||||
/// - context: The LAContext used to authorize the persistent context.
|
||||
/// - duration: The duration of the authorization context, in seconds.
|
||||
init(secret: Secret, context: LAContext, duration: TimeInterval) {
|
||||
self.secret = secret
|
||||
self.context = context
|
||||
let durationInNanoSeconds = Measurement(value: duration, unit: UnitDuration.seconds).converted(to: .nanoseconds).value
|
||||
self.expiration = clock_gettime_nsec_np(CLOCK_MONOTONIC) + UInt64(durationInNanoSeconds)
|
||||
}
|
||||
|
||||
/// A boolean describing whether or not the context is still valid.
|
||||
var valid: Bool {
|
||||
clock_gettime_nsec_np(CLOCK_MONOTONIC) < expiration
|
||||
}
|
||||
}
|
||||
|
||||
}
|
@ -0,0 +1,3 @@
|
||||
# ``SmartCardSecretKit``
|
||||
|
||||
SmartCardSecretKit contains implementations of SecretKit protocols backed by a Smart Card.
|
@ -0,0 +1,14 @@
|
||||
# ``SmartCardSecretKit/SmartCard``
|
||||
|
||||
## Topics
|
||||
|
||||
### Implementations
|
||||
|
||||
- ``Secret``
|
||||
- ``Store``
|
||||
|
||||
### Errors
|
||||
|
||||
- ``KeychainError``
|
||||
- ``SigningError``
|
||||
- ``SecurityError``
|
@ -0,0 +1,2 @@
|
||||
/// Namespace for the Smart Card implementations.
|
||||
public enum SmartCard {}
|
@ -1,8 +1,10 @@
|
||||
import Foundation
|
||||
import Combine
|
||||
import SecretKit
|
||||
|
||||
extension SmartCard {
|
||||
|
||||
/// An implementation of Secret backed by a Smart Card.
|
||||
public struct Secret: SecretKit.Secret {
|
||||
|
||||
public let id: Data
|
@ -2,14 +2,13 @@ import Foundation
|
||||
import Security
|
||||
import CryptoTokenKit
|
||||
import LocalAuthentication
|
||||
import SecretKit
|
||||
|
||||
// TODO: Might need to split this up into "sub-stores?"
|
||||
// ie, each token has its own Store.
|
||||
extension SmartCard {
|
||||
|
||||
/// An implementation of Store backed by a Smart Card.
|
||||
public class Store: SecretStore {
|
||||
|
||||
// TODO: Read actual smart card name, eg "YubiKey 5c"
|
||||
@Published public var isAvailable: Bool = false
|
||||
public let id = UUID()
|
||||
public private(set) var name = NSLocalizedString("Smart Card", comment: "Smart Card")
|
||||
@ -17,6 +16,7 @@ extension SmartCard {
|
||||
private let watcher = TKTokenWatcher()
|
||||
private var tokenID: String?
|
||||
|
||||
/// Initializes a Store.
|
||||
public init() {
|
||||
tokenID = watcher.nonSecureEnclaveTokens.first
|
||||
watcher.setInsertionHandler { string in
|
||||
@ -44,7 +44,7 @@ extension SmartCard {
|
||||
fatalError("Keys must be deleted on the smart card.")
|
||||
}
|
||||
|
||||
public func sign(data: Data, with secret: SecretType, for provenance: SigningRequestProvenance) throws -> Data {
|
||||
public func sign(data: Data, with secret: SecretType, for provenance: SigningRequestProvenance) throws -> SignedData {
|
||||
guard let tokenID = tokenID else { fatalError() }
|
||||
let context = LAContext()
|
||||
context.localizedReason = "sign a request from \"\(provenance.origin.displayName)\" using secret \"\(secret.name)\""
|
||||
@ -56,7 +56,7 @@ extension SmartCard {
|
||||
kSecAttrTokenID: tokenID,
|
||||
kSecUseAuthenticationContext: context,
|
||||
kSecReturnRef: true
|
||||
] as CFDictionary
|
||||
] as CFDictionary
|
||||
var untyped: CFTypeRef?
|
||||
let status = SecItemCopyMatching(attributes, &untyped)
|
||||
if status != errSecSuccess {
|
||||
@ -79,7 +79,10 @@ extension SmartCard {
|
||||
guard let signature = SecKeyCreateSignature(key, signatureAlgorithm, data as CFData, &signError) else {
|
||||
throw SigningError(error: signError)
|
||||
}
|
||||
return signature as Data
|
||||
return SignedData(data: signature as Data, requiredAuthentication: false)
|
||||
}
|
||||
|
||||
public func persistAuthentication(secret: SmartCard.Secret, forDuration: TimeInterval) throws {
|
||||
}
|
||||
|
||||
}
|
||||
@ -88,11 +91,14 @@ extension SmartCard {
|
||||
|
||||
extension SmartCard.Store {
|
||||
|
||||
/// Resets the token ID and reloads secrets.
|
||||
/// - Parameter tokenID: The ID of the token that was removed.
|
||||
private func smartcardRemoved(for tokenID: String? = nil) {
|
||||
self.tokenID = nil
|
||||
reloadSecrets()
|
||||
}
|
||||
|
||||
/// Reloads all secrets from the store.
|
||||
private func reloadSecrets() {
|
||||
DispatchQueue.main.async {
|
||||
self.isAvailable = self.tokenID != nil
|
||||
@ -101,14 +107,25 @@ extension SmartCard.Store {
|
||||
}
|
||||
}
|
||||
|
||||
/// Loads all secrets from the store.
|
||||
private func loadSecrets() {
|
||||
guard let tokenID = tokenID else { return }
|
||||
// Hack to read name if there's only one smart card
|
||||
let slotNames = TKSmartCardSlotManager().slotNames
|
||||
if watcher.nonSecureEnclaveTokens.count == 1 && slotNames.count == 1 {
|
||||
name = slotNames.first!
|
||||
|
||||
let fallbackName = NSLocalizedString("Smart Card", comment: "Smart Card")
|
||||
if #available(macOS 12.0, *) {
|
||||
if let driverName = watcher.tokenInfo(forTokenID: tokenID)?.driverName {
|
||||
name = driverName
|
||||
} else {
|
||||
name = fallbackName
|
||||
}
|
||||
} else {
|
||||
name = NSLocalizedString("Smart Card", comment: "Smart Card")
|
||||
// Hack to read name if there's only one smart card
|
||||
let slotNames = TKSmartCardSlotManager().slotNames
|
||||
if watcher.nonSecureEnclaveTokens.count == 1 && slotNames.count == 1 {
|
||||
name = slotNames.first!
|
||||
} else {
|
||||
name = fallbackName
|
||||
}
|
||||
}
|
||||
|
||||
let attributes = [
|
||||
@ -118,7 +135,7 @@ extension SmartCard.Store {
|
||||
kSecReturnRef: true,
|
||||
kSecMatchLimit: kSecMatchLimitAll,
|
||||
kSecReturnAttributes: true
|
||||
] as CFDictionary
|
||||
] as CFDictionary
|
||||
var untyped: CFTypeRef?
|
||||
SecItemCopyMatching(attributes, &untyped)
|
||||
guard let typed = untyped as? [[CFString: Any]] else { return }
|
||||
@ -140,6 +157,7 @@ extension SmartCard.Store {
|
||||
|
||||
extension TKTokenWatcher {
|
||||
|
||||
/// All available tokens, excluding the Secure Enclave.
|
||||
fileprivate var nonSecureEnclaveTokens: [String] {
|
||||
tokenIDs.filter { !$0.contains("setoken") }
|
||||
}
|
||||
@ -148,11 +166,15 @@ extension TKTokenWatcher {
|
||||
|
||||
extension SmartCard {
|
||||
|
||||
/// A wrapper around an error code reported by a Keychain API.
|
||||
public struct KeychainError: Error {
|
||||
/// The status code involved.
|
||||
public let statusCode: OSStatus
|
||||
}
|
||||
|
||||
/// A signing-related error.
|
||||
public struct SigningError: Error {
|
||||
/// The underlying error reported by the API, if one was returned.
|
||||
public let error: SecurityError?
|
||||
}
|
||||
|
104
Sources/Packages/Tests/BriefTests/ReleaseParsingTests.swift
Normal file
104
Sources/Packages/Tests/BriefTests/ReleaseParsingTests.swift
Normal file
@ -0,0 +1,104 @@
|
||||
import XCTest
|
||||
@testable import Brief
|
||||
|
||||
class ReleaseParsingTests: XCTestCase {
|
||||
|
||||
func testNonCritical() {
|
||||
let release = Release(name: "1.0.0", prerelease: false, html_url: URL(string: "https://example.com")!, body: "Initial release")
|
||||
XCTAssert(release.critical == false)
|
||||
}
|
||||
|
||||
func testCritical() {
|
||||
let release = Release(name: "1.0.0", prerelease: false, html_url: URL(string: "https://example.com")!, body: "Critical Security Update")
|
||||
XCTAssert(release.critical == true)
|
||||
}
|
||||
|
||||
func testOSMissing() {
|
||||
let release = Release(name: "1.0.0", prerelease: false, html_url: URL(string: "https://example.com")!, body: "Critical Security Update")
|
||||
XCTAssert(release.minimumOSVersion == SemVer("11.0.0"))
|
||||
}
|
||||
|
||||
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")
|
||||
XCTAssert(release.minimumOSVersion == SemVer("1.2.3"))
|
||||
}
|
||||
|
||||
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")
|
||||
XCTAssert(release.minimumOSVersion == SemVer("1.2.3"))
|
||||
}
|
||||
|
||||
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")
|
||||
XCTAssert(release.minimumOSVersion == SemVer("1.2.3"))
|
||||
}
|
||||
|
||||
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")
|
||||
XCTAssert(release.minimumOSVersion < SemVer("11.0.0"))
|
||||
}
|
||||
|
||||
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")
|
||||
XCTAssert(release.minimumOSVersion <= SemVer("11.2.3"))
|
||||
}
|
||||
|
||||
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")
|
||||
XCTAssert(release.minimumOSVersion > SemVer("1.0.0"))
|
||||
}
|
||||
|
||||
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"))
|
||||
let two = Release(name: "2.0.0", prerelease: false, html_url: URL(string: "https://example.com")!, body: "2.0 available! Minimum macOS Version: 2.2.3")
|
||||
let releases = [
|
||||
Release(name: "1.0.0", prerelease: false, html_url: URL(string: "https://example.com")!, body: "Initial release Minimum macOS Version: 1.2.3"),
|
||||
Release(name: "1.0.1", prerelease: false, html_url: URL(string: "https://example.com")!, body: "Bug fixes Minimum macOS Version: 1.2.3"),
|
||||
two,
|
||||
Release(name: "1.0.2", prerelease: false, html_url: URL(string: "https://example.com")!, body: "Emergency patch! Minimum macOS Version: 1.2.3"),
|
||||
]
|
||||
|
||||
let expectation = XCTestExpectation()
|
||||
updater.evaluate(releases: releases)
|
||||
DispatchQueue.main.async {
|
||||
XCTAssert(updater.update == two)
|
||||
expectation.fulfill()
|
||||
}
|
||||
wait(for: [expectation], timeout: 1)
|
||||
}
|
||||
|
||||
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"))
|
||||
let oneOhTwo = Release(name: "1.0.2", prerelease: false, html_url: URL(string: "https://example.com")!, body: "Emergency patch! Minimum macOS Version: 1.2.3")
|
||||
let releases = [
|
||||
Release(name: "1.0.0", prerelease: false, html_url: URL(string: "https://example.com")!, body: "Initial release Minimum macOS Version: 1.2.3"),
|
||||
Release(name: "1.0.1", prerelease: false, html_url: URL(string: "https://example.com")!, body: "Bug fixes Minimum macOS Version: 1.2.3"),
|
||||
Release(name: "2.0.0", prerelease: false, html_url: URL(string: "https://example.com")!, body: "2.0 available! Minimum macOS Version: 2.2.3"),
|
||||
Release(name: "1.0.2", prerelease: false, html_url: URL(string: "https://example.com")!, body: "Emergency patch! Minimum macOS Version: 1.2.3"),
|
||||
]
|
||||
let expectation = XCTestExpectation()
|
||||
updater.evaluate(releases: releases)
|
||||
DispatchQueue.main.async {
|
||||
XCTAssert(updater.update == oneOhTwo)
|
||||
expectation.fulfill()
|
||||
}
|
||||
wait(for: [expectation], timeout: 1)
|
||||
}
|
||||
|
||||
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"),
|
||||
Release(name: "1.0.1", prerelease: false, html_url: URL(string: "https://example.com")!, body: "Bug fixes"),
|
||||
two,
|
||||
Release(name: "1.0.2", prerelease: false, html_url: URL(string: "https://example.com")!, body: "Emergency patch!"),
|
||||
]
|
||||
let sorted = releases.sorted().reversed().first
|
||||
XCTAssert(sorted == two)
|
||||
}
|
||||
|
||||
}
|
@ -27,6 +27,21 @@ class SemVerTests: XCTestCase {
|
||||
XCTAssert(current < new)
|
||||
}
|
||||
|
||||
func testRegularParsing() {
|
||||
let current = SemVer("1.0.2")
|
||||
XCTAssert(current.versionNumbers == [1, 0, 2])
|
||||
}
|
||||
|
||||
func testNoPatch() {
|
||||
let current = SemVer("1.1")
|
||||
XCTAssert(current.versionNumbers == [1, 1, 0])
|
||||
}
|
||||
|
||||
func testGarbage() {
|
||||
let current = SemVer("Test")
|
||||
XCTAssert(current.versionNumbers == [0, 0, 0])
|
||||
}
|
||||
|
||||
func testBeta() {
|
||||
let current = SemVer("1.0.2")
|
||||
let new = SemVer("1.1.0_beta1")
|
@ -1,3 +1,4 @@
|
||||
import Foundation
|
||||
import SecretAgentKit
|
||||
|
||||
class StubFileHandleWriter: FileHandleWriter {
|
@ -1,3 +1,4 @@
|
||||
import Foundation
|
||||
import SecretKit
|
||||
import CryptoKit
|
||||
|
||||
@ -48,9 +49,9 @@ extension Stub {
|
||||
print("Public Key OpenSSH: \(OpenSSHKeyWriter().openSSHString(secret: secret))")
|
||||
}
|
||||
|
||||
public func sign(data: Data, with secret: Secret, for provenance: SigningRequestProvenance) throws -> Data {
|
||||
public func sign(data: Data, with secret: Secret, for provenance: SigningRequestProvenance) throws -> SignedData {
|
||||
guard !shouldThrow else {
|
||||
throw NSError()
|
||||
throw NSError(domain: "test", code: 0, userInfo: nil)
|
||||
}
|
||||
let privateKey = SecKeyCreateWithData(secret.privateKey as CFData, [
|
||||
kSecAttrKeyType: kSecAttrKeyTypeECSECPrimeRandom,
|
||||
@ -67,7 +68,10 @@ extension Stub {
|
||||
default:
|
||||
fatalError()
|
||||
}
|
||||
return SecKeyCreateSignature(privateKey, signatureAlgorithm, data as CFData, nil)! as Data
|
||||
return SignedData(data: SecKeyCreateSignature(privateKey, signatureAlgorithm, data as CFData, nil)! as Data, requiredAuthentication: false)
|
||||
}
|
||||
|
||||
public func persistAuthentication(secret: Stub.Secret, forDuration duration: TimeInterval) throws {
|
||||
}
|
||||
|
||||
}
|
@ -10,14 +10,14 @@ struct StubWitness {
|
||||
|
||||
extension StubWitness: SigningWitness {
|
||||
|
||||
func speakNowOrForeverHoldYourPeace(forAccessTo secret: AnySecret, by provenance: SigningRequestProvenance) throws {
|
||||
func speakNowOrForeverHoldYourPeace(forAccessTo secret: AnySecret, from store: AnySecretStore, by provenance: SigningRequestProvenance) throws {
|
||||
let objection = speakNow(secret, provenance)
|
||||
if objection {
|
||||
throw TheresMyChance()
|
||||
}
|
||||
}
|
||||
|
||||
func witness(accessTo secret: AnySecret, by provenance: SigningRequestProvenance) throws {
|
||||
func witness(accessTo secret: AnySecret, from store: AnySecretStore, by provenance: SigningRequestProvenance, requiredAuthentication: Bool) throws {
|
||||
witness(secret, provenance)
|
||||
}
|
||||
|
@ -1,6 +1,8 @@
|
||||
import Foundation
|
||||
import XCTest
|
||||
@testable import SecretKit
|
||||
@testable import SecureEnclaveSecretKit
|
||||
@testable import SmartCardSecretKit
|
||||
|
||||
class AnySecretTests: XCTestCase {
|
||||
|
@ -1,6 +1,8 @@
|
||||
import Foundation
|
||||
import XCTest
|
||||
@testable import SecretKit
|
||||
@testable import SecureEnclaveSecretKit
|
||||
@testable import SmartCardSecretKit
|
||||
|
||||
class OpenSSHReaderTests: XCTestCase {
|
||||
|
@ -1,13 +1,19 @@
|
||||
import Foundation
|
||||
import XCTest
|
||||
@testable import SecretKit
|
||||
@testable import SecureEnclaveSecretKit
|
||||
@testable import SmartCardSecretKit
|
||||
|
||||
class OpenSSHWriterTests: XCTestCase {
|
||||
|
||||
let writer = OpenSSHKeyWriter()
|
||||
|
||||
func testECDSA256Fingerprint() {
|
||||
XCTAssertEqual(writer.openSSHFingerprint(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")
|
||||
}
|
||||
|
||||
func testECDSA256SHA256Fingerprint() {
|
||||
XCTAssertEqual(writer.openSSHSHA256Fingerprint(secret: Constants.ecdsa256Secret), "SHA256:/VQFeGyM8qKA8rB6WGMuZZxZLJln2UgXLk3F0uTF650")
|
||||
}
|
||||
|
||||
func testECDSA256PublicKey() {
|
||||
@ -19,8 +25,12 @@ class OpenSSHWriterTests: XCTestCase {
|
||||
XCTAssertEqual(writer.data(secret: Constants.ecdsa256Secret), Data(base64Encoded: "AAAAE2VjZHNhLXNoYTItbmlzdHAyNTYAAAAIbmlzdHAyNTYAAABBBOVEjgAA5PHqRgwykjN5qM21uWCHFSY/Sqo5gkHAkn+e1MMQKHOLga7ucB9b3mif33MBid59GRK9GEPVlMiSQwo="))
|
||||
}
|
||||
|
||||
func testECDSA384Fingerprint() {
|
||||
XCTAssertEqual(writer.openSSHFingerprint(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")
|
||||
}
|
||||
|
||||
func testECDSA384SHA256Fingerprint() {
|
||||
XCTAssertEqual(writer.openSSHSHA256Fingerprint(secret: Constants.ecdsa384Secret), "SHA256:GJUEymQNL9ymaMRRJCMGY4rWIJHu/Lm8Yhao/PAiz1I")
|
||||
}
|
||||
|
||||
func testECDSA384PublicKey() {
|
@ -2,6 +2,8 @@ import Cocoa
|
||||
import OSLog
|
||||
import Combine
|
||||
import SecretKit
|
||||
import SecureEnclaveSecretKit
|
||||
import SmartCardSecretKit
|
||||
import SecretAgentKit
|
||||
import Brief
|
||||
|
||||
@ -16,6 +18,7 @@ class AppDelegate: NSObject, NSApplicationDelegate {
|
||||
}()
|
||||
private let updater = Updater(checkOnLaunch: false)
|
||||
private let notifier = Notifier()
|
||||
private let publicKeyFileStoreController = PublicKeyFileStoreController(homeDirectory: NSHomeDirectory())
|
||||
private lazy var agent: Agent = {
|
||||
Agent(storeList: storeList, witness: notifier)
|
||||
}()
|
||||
@ -30,6 +33,10 @@ class AppDelegate: NSObject, NSApplicationDelegate {
|
||||
DispatchQueue.main.async {
|
||||
self.socketController.handler = self.agent.handle(reader:writer:)
|
||||
}
|
||||
NotificationCenter.default.addObserver(forName: .secretStoreReloaded, object: nil, queue: .main) { [self] _ in
|
||||
try? publicKeyFileStoreController.generatePublicKeys(for: storeList.stores.flatMap({ $0.secrets }), clear: true)
|
||||
}
|
||||
try? publicKeyFileStoreController.generatePublicKeys(for: storeList.stores.flatMap({ $0.secrets }), clear: true)
|
||||
notifier.prompt()
|
||||
updateSink = updater.$update.sink { update in
|
||||
guard let update = update else { return }
|
||||
@ -37,6 +44,5 @@ class AppDelegate: NSObject, NSApplicationDelegate {
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
}
|
||||
|
Before Width: | Height: | Size: 16 KiB After Width: | Height: | Size: 16 KiB |
Before Width: | Height: | Size: 40 KiB After Width: | Height: | Size: 40 KiB |
31
Sources/SecretAgent/InternetAccessPolicy.plist
Normal file
31
Sources/SecretAgent/InternetAccessPolicy.plist
Normal file
@ -0,0 +1,31 @@
|
||||
<?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>ApplicationDescription</key>
|
||||
<string>Secretive is an app for storing and managing SSH keys in the Secure Enclave. SecretAgent is a helper process that runs in the background to sign requests, so that you don't always have to keep the main Secretive app open.</string>
|
||||
<key>DeveloperName</key>
|
||||
<string>Max Goedjen</string>
|
||||
<key>Website</key>
|
||||
<string>https://github.com/maxgoedjen/secretive</string>
|
||||
<key>Connections</key>
|
||||
<array>
|
||||
<dict>
|
||||
<key>IsIncoming</key>
|
||||
<false/>
|
||||
<key>Host</key>
|
||||
<string>api.github.com</string>
|
||||
<key>NetworkProtocol</key>
|
||||
<string>TCP</string>
|
||||
<key>Port</key>
|
||||
<string>443</string>
|
||||
<key>Purpose</key>
|
||||
<string>Secretive checks GitHub for new versions and security updates.</string>
|
||||
<key>DenyConsequences</key>
|
||||
<string>If you deny these connections, you will not be notified about new versions and critical security updates.</string>
|
||||
</dict>
|
||||
</array>
|
||||
<key>Services</key>
|
||||
<array/>
|
||||
</dict>
|
||||
</plist>
|
187
Sources/SecretAgent/Notifier.swift
Normal file
187
Sources/SecretAgent/Notifier.swift
Normal file
@ -0,0 +1,187 @@
|
||||
import Foundation
|
||||
import UserNotifications
|
||||
import AppKit
|
||||
import SecretKit
|
||||
import SecretAgentKit
|
||||
import Brief
|
||||
|
||||
class Notifier {
|
||||
|
||||
private let notificationDelegate = NotificationDelegate()
|
||||
|
||||
init() {
|
||||
let updateAction = UNNotificationAction(identifier: Constants.updateActionIdentitifier, title: "Update", options: [])
|
||||
let ignoreAction = UNNotificationAction(identifier: Constants.ignoreActionIdentitifier, title: "Ignore", options: [])
|
||||
let updateCategory = UNNotificationCategory(identifier: Constants.updateCategoryIdentitifier, actions: [updateAction, ignoreAction], intentIdentifiers: [], options: [])
|
||||
let criticalUpdateCategory = UNNotificationCategory(identifier: Constants.criticalUpdateCategoryIdentitifier, actions: [updateAction], intentIdentifiers: [], options: [])
|
||||
|
||||
let rawDurations = [
|
||||
Measurement(value: 1, unit: UnitDuration.minutes),
|
||||
Measurement(value: 5, unit: UnitDuration.minutes),
|
||||
Measurement(value: 1, unit: UnitDuration.hours),
|
||||
Measurement(value: 24, unit: UnitDuration.hours)
|
||||
]
|
||||
|
||||
let doNotPersistAction = UNNotificationAction(identifier: Constants.doNotPersistActionIdentitifier, title: "Do Not Unlock", options: [])
|
||||
var allPersistenceActions = [doNotPersistAction]
|
||||
|
||||
let formatter = DateComponentsFormatter()
|
||||
formatter.unitsStyle = .spellOut
|
||||
formatter.allowedUnits = [.hour, .minute, .day]
|
||||
|
||||
for duration in rawDurations {
|
||||
let seconds = duration.converted(to: .seconds).value
|
||||
guard let string = formatter.string(from: seconds)?.capitalized else { continue }
|
||||
let identifier = Constants.persistAuthenticationCategoryIdentitifier.appending("\(seconds)")
|
||||
let action = UNNotificationAction(identifier: identifier, title: string, options: [])
|
||||
notificationDelegate.persistOptions[identifier] = seconds
|
||||
allPersistenceActions.append(action)
|
||||
}
|
||||
|
||||
let persistAuthenticationCategory = UNNotificationCategory(identifier: Constants.persistAuthenticationCategoryIdentitifier, actions: allPersistenceActions, intentIdentifiers: [], options: [])
|
||||
if persistAuthenticationCategory.responds(to: Selector(("actionsMenuTitle"))) {
|
||||
persistAuthenticationCategory.setValue("Leave Unlocked", forKey: "_actionsMenuTitle")
|
||||
}
|
||||
UNUserNotificationCenter.current().setNotificationCategories([updateCategory, criticalUpdateCategory, persistAuthenticationCategory])
|
||||
UNUserNotificationCenter.current().delegate = notificationDelegate
|
||||
|
||||
notificationDelegate.persistAuthentication = { secret, store, duration in
|
||||
guard let duration = duration else { return }
|
||||
try? store.persistAuthentication(secret: secret, forDuration: duration)
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
func prompt() {
|
||||
let notificationCenter = UNUserNotificationCenter.current()
|
||||
notificationCenter.requestAuthorization(options: .alert) { _, _ in }
|
||||
}
|
||||
|
||||
func notify(accessTo secret: AnySecret, from store: AnySecretStore, by provenance: SigningRequestProvenance, requiredAuthentication: Bool) {
|
||||
notificationDelegate.pendingPersistableSecrets[secret.id.description] = secret
|
||||
notificationDelegate.pendingPersistableStores[store.id.description] = store
|
||||
let notificationCenter = UNUserNotificationCenter.current()
|
||||
let notificationContent = UNMutableNotificationContent()
|
||||
notificationContent.title = "Signed Request from \(provenance.origin.displayName)"
|
||||
notificationContent.subtitle = "Using secret \"\(secret.name)\""
|
||||
notificationContent.userInfo[Constants.persistSecretIDKey] = secret.id.description
|
||||
notificationContent.userInfo[Constants.persistStoreIDKey] = store.id.description
|
||||
if #available(macOS 12.0, *) {
|
||||
notificationContent.interruptionLevel = .timeSensitive
|
||||
}
|
||||
if requiredAuthentication {
|
||||
notificationContent.categoryIdentifier = Constants.persistAuthenticationCategoryIdentitifier
|
||||
}
|
||||
if let iconURL = provenance.origin.iconURL, let attachment = try? UNNotificationAttachment(identifier: "icon", url: iconURL, options: nil) {
|
||||
notificationContent.attachments = [attachment]
|
||||
}
|
||||
let request = UNNotificationRequest(identifier: UUID().uuidString, content: notificationContent, trigger: nil)
|
||||
notificationCenter.add(request, withCompletionHandler: nil)
|
||||
}
|
||||
|
||||
func notify(update: Release, ignore: ((Release) -> Void)?) {
|
||||
notificationDelegate.release = update
|
||||
notificationDelegate.ignore = ignore
|
||||
let notificationCenter = UNUserNotificationCenter.current()
|
||||
let notificationContent = UNMutableNotificationContent()
|
||||
if update.critical {
|
||||
if #available(macOS 12.0, *) {
|
||||
notificationContent.interruptionLevel = .critical
|
||||
}
|
||||
notificationContent.title = "Critical Security Update - \(update.name)"
|
||||
} else {
|
||||
notificationContent.title = "Update Available - \(update.name)"
|
||||
}
|
||||
notificationContent.subtitle = "Click to Update"
|
||||
notificationContent.body = update.body
|
||||
notificationContent.categoryIdentifier = update.critical ? Constants.criticalUpdateCategoryIdentitifier : Constants.updateCategoryIdentitifier
|
||||
let request = UNNotificationRequest(identifier: UUID().uuidString, content: notificationContent, trigger: nil)
|
||||
notificationCenter.add(request, withCompletionHandler: nil)
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
extension Notifier: SigningWitness {
|
||||
|
||||
func speakNowOrForeverHoldYourPeace(forAccessTo secret: AnySecret, from store: AnySecretStore, by provenance: SigningRequestProvenance) throws {
|
||||
}
|
||||
|
||||
func witness(accessTo secret: AnySecret, from store: AnySecretStore, by provenance: SigningRequestProvenance, requiredAuthentication: Bool) throws {
|
||||
notify(accessTo: secret, from: store, by: provenance, requiredAuthentication: requiredAuthentication)
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
extension Notifier {
|
||||
|
||||
enum Constants {
|
||||
|
||||
// Update notifications
|
||||
static let updateCategoryIdentitifier = "com.maxgoedjen.Secretive.SecretAgent.update"
|
||||
static let criticalUpdateCategoryIdentitifier = "com.maxgoedjen.Secretive.SecretAgent.update.critical"
|
||||
static let updateActionIdentitifier = "com.maxgoedjen.Secretive.SecretAgent.update.updateaction"
|
||||
static let ignoreActionIdentitifier = "com.maxgoedjen.Secretive.SecretAgent.update.ignoreaction"
|
||||
|
||||
// Authorization persistence notificatoins
|
||||
static let persistAuthenticationCategoryIdentitifier = "com.maxgoedjen.Secretive.SecretAgent.persistauthentication"
|
||||
static let doNotPersistActionIdentitifier = "com.maxgoedjen.Secretive.SecretAgent.persistauthentication.donotpersist"
|
||||
static let persistForActionIdentitifierPrefix = "com.maxgoedjen.Secretive.SecretAgent.persistauthentication.persist."
|
||||
|
||||
static let persistSecretIDKey = "com.maxgoedjen.Secretive.SecretAgent.persistauthentication.secretidkey"
|
||||
static let persistStoreIDKey = "com.maxgoedjen.Secretive.SecretAgent.persistauthentication.storeidkey"
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
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] = [:]
|
||||
|
||||
func userNotificationCenter(_ center: UNUserNotificationCenter, openSettingsFor notification: UNNotification?) {
|
||||
|
||||
}
|
||||
|
||||
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:
|
||||
handlePersistAuthenticationResponse(response: response)
|
||||
default:
|
||||
fatalError()
|
||||
}
|
||||
|
||||
completionHandler()
|
||||
}
|
||||
|
||||
func handleUpdateResponse(response: UNNotificationResponse) {
|
||||
guard let update = release else { return }
|
||||
switch response.actionIdentifier {
|
||||
case Notifier.Constants.updateActionIdentitifier, UNNotificationDefaultActionIdentifier:
|
||||
NSWorkspace.shared.open(update.html_url)
|
||||
case Notifier.Constants.ignoreActionIdentitifier:
|
||||
ignore?(update)
|
||||
default:
|
||||
fatalError()
|
||||
}
|
||||
}
|
||||
|
||||
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, withCompletionHandler completionHandler: @escaping (UNNotificationPresentationOptions) -> Void) {
|
||||
completionHandler([.list, .banner])
|
||||
}
|
||||
|
||||
}
|
1027
Sources/Secretive.xcodeproj/project.pbxproj
Normal file
1027
Sources/Secretive.xcodeproj/project.pbxproj
Normal file
File diff suppressed because it is too large
Load Diff
@ -1,6 +1,6 @@
|
||||
<?xml version="1.0" encoding="UTF-8"?>
|
||||
<Scheme
|
||||
LastUpgradeVersion = "1140"
|
||||
LastUpgradeVersion = "1320"
|
||||
version = "1.7">
|
||||
<BuildAction
|
||||
parallelizeBuildables = "YES"
|
@ -1,6 +1,6 @@
|
||||
<?xml version="1.0" encoding="UTF-8"?>
|
||||
<Scheme
|
||||
LastUpgradeVersion = "1140"
|
||||
LastUpgradeVersion = "1320"
|
||||
version = "1.7">
|
||||
<BuildAction
|
||||
parallelizeBuildables = "YES"
|
@ -1,6 +1,8 @@
|
||||
import Cocoa
|
||||
import SwiftUI
|
||||
import SecretKit
|
||||
import SecureEnclaveSecretKit
|
||||
import SmartCardSecretKit
|
||||
import Brief
|
||||
|
||||
@main
|
||||
@ -36,7 +38,7 @@ struct Secretive: App {
|
||||
if agentStatusChecker.running && justUpdatedChecker.justUpdated {
|
||||
// Relaunch the agent, since it'll be running from earlier update still
|
||||
reinstallAgent()
|
||||
} else if !agentStatusChecker.running {
|
||||
} else if !agentStatusChecker.running && !agentStatusChecker.developmentBuild {
|
||||
forceLaunchAgent()
|
||||
}
|
||||
}
|
Some files were not shown because too many files have changed in this diff Show More
Reference in New Issue
Block a user