Compare commits
340 Commits
v0.3.2
...
maxgoedjen
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
4e589f0e90 | ||
|
|
b82a52f172 | ||
|
|
c63d87cbec | ||
|
|
65bc6c1a69 | ||
|
|
275b6ef9bb | ||
|
|
f13bc23991 | ||
|
|
3a67d59519 | ||
|
|
d9a3f0c813 | ||
|
|
84d5a56fb0 | ||
|
|
14b60cee36 | ||
|
|
3bb0cc4a0e | ||
|
|
516e37fdde | ||
|
|
5df845ca6e | ||
|
|
f9dc947b59 | ||
|
|
9c042d1956 | ||
|
|
08e0c4b63b | ||
|
|
f80cbdaf04 | ||
|
|
7a53a85615 | ||
|
|
1f74bd814f | ||
|
|
d9d93574f2 | ||
|
|
15e8ed1ec2 | ||
|
|
1df0c8e96b | ||
|
|
8213a8b451 | ||
|
|
af77fd4a21 | ||
|
|
85d0cab0f5 | ||
|
|
e8cdcdfb7f | ||
|
|
d7f8d5e56b | ||
|
|
3f247d628f | ||
|
|
dae9cead4e | ||
|
|
fe9f8613fa | ||
|
|
5d5ae5bab4 | ||
|
|
f76766a9d5 | ||
|
|
b308b10716 | ||
|
|
0e1e6813a1 | ||
|
|
27bf7c29e4 | ||
|
|
36b6c52979 | ||
|
|
67ec4fee12 | ||
|
|
21fc834fd9 | ||
|
|
726d0580d0 | ||
|
|
4f608ebbc6 | ||
|
|
6e7cf82618 | ||
|
|
6d9b2f9744 | ||
|
|
96ef91df0c | ||
|
|
aa46d8fa48 | ||
|
|
cf7c6e9fbe | ||
|
|
9d05a43e15 | ||
|
|
7c7db56c1e | ||
|
|
cd12e4c828 | ||
|
|
a5b43ea046 | ||
|
|
8c516e128a | ||
|
|
6854c05763 | ||
|
|
5467474d88 | ||
|
|
5c2d039682 | ||
|
|
20e64604d6 | ||
|
|
c5a610d786 | ||
|
|
7d21e3983c | ||
|
|
2c38aaed6f | ||
|
|
63b42bd9df | ||
|
|
cf5ae49ebc | ||
|
|
61705af42f | ||
|
|
558ae15b2d | ||
|
|
902d5c4a1e | ||
|
|
e0c24917f2 | ||
|
|
3d5f0b45bd | ||
|
|
74f4f1c0b1 | ||
|
|
c8cf0db1c5 | ||
|
|
412687467b | ||
|
|
416a7d5f40 | ||
|
|
c4605fb60e | ||
|
|
61eed5987c | ||
|
|
cbef7c6181 | ||
|
|
63a09390b8 | ||
|
|
a4e1ab9eb6 | ||
|
|
147f4d9908 | ||
|
|
ddcb2a36ec | ||
|
|
6dc93806a8 | ||
|
|
99a6d48e53 | ||
|
|
935ac32ea2 | ||
|
|
a0a632f245 | ||
|
|
51fed9e593 | ||
|
|
f652d1d961 | ||
|
|
8aacd428b1 | ||
|
|
c2eb5ce1f6 | ||
|
|
fb4dec383b | ||
|
|
c5052dd457 | ||
|
|
d967c7de07 | ||
|
|
d5b6382dd0 | ||
|
|
e8fcb95db0 | ||
|
|
8ad2d60082 | ||
|
|
6ce0510f21 | ||
|
|
c52728a050 | ||
|
|
8f4d0b8eda | ||
|
|
c37d0c0cba | ||
|
|
6c607f065c | ||
|
|
cff1fde90e | ||
|
|
c32ceb6ad8 | ||
|
|
f0a6f2e43b | ||
|
|
828c61cb2f | ||
|
|
e8c5336888 | ||
|
|
b3bea27f40 | ||
|
|
3d3d123484 | ||
|
|
5b0135d694 | ||
|
|
5067f05558 | ||
|
|
b815c1e5ad | ||
|
|
75c9b5bb62 | ||
|
|
f259cf6bf3 | ||
|
|
2ba73ff680 | ||
|
|
e3938caecb | ||
|
|
bd096c3012 | ||
|
|
2355d3f989 | ||
|
|
45bcb03fef | ||
|
|
e86aa559a4 | ||
|
|
d36537b919 | ||
|
|
8adb4423ac | ||
|
|
8dbf992cce | ||
|
|
f382d72ee5 | ||
|
|
9749cd6f3e | ||
|
|
83ecc15332 | ||
|
|
ecd001a082 | ||
|
|
eeec2c3169 | ||
|
|
609adf04bf | ||
|
|
197f63d1eb | ||
|
|
efe5858ce1 | ||
|
|
ed2678a615 | ||
|
|
0e6b218f1f | ||
|
|
5cc62b628a | ||
|
|
feffdb4856 | ||
|
|
c7d28678e7 | ||
|
|
b5f2dfd153 | ||
|
|
ad56019901 | ||
|
|
5929137f20 | ||
|
|
35a7c99cba | ||
|
|
a543de0737 | ||
|
|
fc21018eb4 | ||
|
|
52cc08424e | ||
|
|
d13f4ee7ba | ||
|
|
6f4226f97a | ||
|
|
3315a4bfbc | ||
|
|
85a7a64bc9 | ||
|
|
409efa5f9f | ||
|
|
bb63ae8469 | ||
|
|
30c1d36974 | ||
|
|
de8d18f9e9 | ||
|
|
1ae0996e2c | ||
|
|
3d50a99430 | ||
|
|
45fc356f0f | ||
|
|
212678b94e | ||
|
|
2e1f4881a9 | ||
|
|
c2b80e3c7c | ||
|
|
15d2afd2cb | ||
|
|
2a4da36c4e | ||
|
|
1fc8fa25d9 | ||
|
|
5718ae6805 | ||
|
|
5af84583ab | ||
|
|
afc54c5e40 | ||
|
|
c80a6f1b0b | ||
|
|
8c67ea7c73 | ||
|
|
171981de9f | ||
|
|
cf58630065 | ||
|
|
7b0ccbcc16 | ||
|
|
dbaa57a05a | ||
|
|
6248ecc9db | ||
|
|
d82bb80e14 | ||
|
|
5bf5be6c25 | ||
|
|
1d4ef12546 | ||
|
|
df10fa3912 | ||
|
|
e04fe419ed | ||
|
|
0944d65ccb | ||
|
|
2ca8279187 | ||
|
|
be58ddd324 | ||
|
|
93e79470b7 | ||
|
|
43a9e287c3 | ||
|
|
f54b2a33bf | ||
|
|
3bd8e3b494 | ||
|
|
14b351abee | ||
|
|
480ef5392d | ||
|
|
8679ca3da0 | ||
|
|
f43571baa3 | ||
|
|
acdf0baf3a | ||
|
|
1a362ef955 | ||
|
|
3b254d33a5 | ||
|
|
382913cb99 | ||
|
|
20cbaac6f6 | ||
|
|
47d736cb0d | ||
|
|
fa0e81cd8e | ||
|
|
e31db0f4fa | ||
|
|
403709ac83 | ||
|
|
5f055efa18 | ||
|
|
e77812c06c | ||
|
|
8744313ba1 | ||
|
|
26d6ced9ee | ||
|
|
71b4780488 | ||
|
|
84dd9403c3 | ||
|
|
0af7b803bc | ||
|
|
a1009d0dac | ||
|
|
ae7394f771 | ||
|
|
6ea0a3ebd2 | ||
|
|
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 | ||
|
|
a368acea62 | ||
|
|
76514d410b | ||
|
|
08b5c7b13c | ||
|
|
f801853878 | ||
|
|
3c9659bd06 | ||
|
|
4d4b20c38d | ||
|
|
1f0100ff2d | ||
|
|
59ec40c611 | ||
|
|
edf01cc6d4 | ||
|
|
de21e1040e | ||
|
|
d47c5424ad | ||
|
|
b85acebae1 | ||
|
|
4d4619bdd8 | ||
|
|
50adf4cd48 | ||
|
|
dc5c21c568 | ||
|
|
3328ada3bf | ||
|
|
3774352dfd | ||
|
|
85e096f8cc | ||
|
|
331e4ed0d6 | ||
|
|
4cc312d4fa | ||
|
|
f3d70a57c5 | ||
|
|
55b57e0cbf | ||
|
|
82dcb76ee6 | ||
|
|
bd0e27060c | ||
|
|
393f2797ab | ||
|
|
f1bf863a9d | ||
|
|
c09d1e4020 | ||
|
|
52225ab5e3 | ||
|
|
8b7e3f6b87 | ||
|
|
bc25576c1f | ||
|
|
b234100aa5 | ||
|
|
bc0a45366a | ||
|
|
6dbb3b7fb3 | ||
|
|
8bbf489146 | ||
|
|
30148ee3a4 | ||
|
|
c306801149 | ||
|
|
9c60a0b7dd | ||
|
|
5b38ef00c1 | ||
|
|
ccbf92785d | ||
|
|
f1e8e43f62 | ||
|
|
7b1563f167 | ||
|
|
cca070dbe4 | ||
|
|
31e51e45c1 | ||
|
|
4bfb3a0012 | ||
|
|
a0ed880386 | ||
|
|
92b9648e04 | ||
|
|
4a2a342670 | ||
|
|
1d147d8e34 | ||
|
|
4dcc9b113d | ||
|
|
1f7ebcfe75 | ||
|
|
b090a96975 | ||
|
|
594d855f19 | ||
|
|
89f0798576 | ||
|
|
0d74f6f561 | ||
|
|
efeb7f09a3 | ||
|
|
104199cf53 | ||
|
|
f214da98a4 | ||
|
|
95cf88d3ca | ||
|
|
04835fa437 | ||
|
|
31dfba8265 | ||
|
|
df8eedebd0 | ||
|
|
0a9ecb039e | ||
|
|
2e9a3eb90d | ||
|
|
df599fbe62 | ||
|
|
7c60e9b04b | ||
|
|
f7f182ec77 | ||
|
|
a0052e8395 | ||
|
|
10d3fa150c | ||
|
|
c5abca4099 | ||
|
|
f674d47507 | ||
|
|
1e3ece600d | ||
|
|
7481498c5b | ||
|
|
a6fbcdbe55 | ||
|
|
36e655e527 | ||
|
|
dd3acf5ae1 | ||
|
|
2257e1e190 | ||
|
|
fe16e4d9c4 | ||
|
|
1caf65c68d | ||
|
|
85eb4983bc | ||
|
|
5a2d3ecc2e | ||
|
|
32f0ed88f4 | ||
|
|
d35c58509b | ||
|
|
f810b185f0 | ||
|
|
5ef1fe996b | ||
|
|
2b5fdf541d | ||
|
|
4b66e874a7 | ||
|
|
aa52da2c04 |
1
.github/FUNDING.yml
vendored
Normal file
@@ -0,0 +1 @@
|
||||
github: maxgoedjen
|
||||
BIN
.github/readme/app-dark.png
vendored
Normal file
|
After Width: | Height: | Size: 668 KiB |
BIN
.github/readme/app-light.png
vendored
Normal file
|
After Width: | Height: | Size: 618 KiB |
BIN
.github/readme/app.png
vendored
|
Before Width: | Height: | Size: 348 KiB |
BIN
.github/readme/apple_watch_auth_mac.png
vendored
Normal file
|
After Width: | Height: | Size: 192 KiB |
BIN
.github/readme/apple_watch_auth_watch.png
vendored
Normal file
|
After Width: | Height: | Size: 26 KiB |
BIN
.github/readme/apple_watch_system_prefs.png
vendored
Normal file
|
After Width: | Height: | Size: 631 KiB |
BIN
.github/readme/notification.png
vendored
|
Before Width: | Height: | Size: 1.5 MiB After Width: | Height: | Size: 47 KiB |
BIN
.github/readme/touchid.png
vendored
|
Before Width: | Height: | Size: 135 KiB After Width: | Height: | Size: 230 KiB |
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
|
||||
|
||||
16
.github/templates/release.md
vendored
Normal file
@@ -0,0 +1,16 @@
|
||||
Update description
|
||||
|
||||
## Features
|
||||
|
||||
|
||||
## Fixes
|
||||
|
||||
|
||||
## Minimum macOS Version
|
||||
|
||||
|
||||
## Build
|
||||
https://github.com/maxgoedjen/secretive/actions/runs/RUN_ID
|
||||
|
||||
## Attestation
|
||||
https://github.com/maxgoedjen/secretive/attestations/ATTESTATION_ID
|
||||
47
.github/workflows/codeql.yml
vendored
Normal file
@@ -0,0 +1,47 @@
|
||||
name: "CodeQL Advanced"
|
||||
|
||||
on:
|
||||
push:
|
||||
branches: [ "main" ]
|
||||
pull_request:
|
||||
branches: [ "main" ]
|
||||
schedule:
|
||||
- cron: '26 15 * * 3'
|
||||
|
||||
jobs:
|
||||
analyze:
|
||||
name: Analyze (${{ matrix.language }})
|
||||
runs-on: ${{ (matrix.language == 'swift' && 'macos-26') || 'ubuntu-latest' }}
|
||||
permissions:
|
||||
security-events: write
|
||||
packages: read
|
||||
actions: read
|
||||
contents: read
|
||||
|
||||
strategy:
|
||||
fail-fast: false
|
||||
matrix:
|
||||
include:
|
||||
- language: actions
|
||||
build-mode: none
|
||||
# Disable this until CodeQL supports Xcode 26 builds.
|
||||
- language: swift
|
||||
build-mode: manual
|
||||
steps:
|
||||
- name: Checkout repository
|
||||
uses: actions/checkout@v4
|
||||
- name: Initialize CodeQL
|
||||
uses: github/codeql-action/init@v3
|
||||
with:
|
||||
languages: ${{ matrix.language }}
|
||||
build-mode: ${{ matrix.build-mode }}
|
||||
- if: matrix.build-mode == 'manual'
|
||||
name: "Select Xcode"
|
||||
run: sudo xcrun xcode-select -s /Applications/Xcode_26.0.app
|
||||
- if: matrix.build-mode == 'manual'
|
||||
name: "Build"
|
||||
run: xcrun xcodebuild -project Sources/Secretive.xcodeproj -scheme Secretive CODE_SIGN_IDENTITY="" CODE_SIGNING_REQUIRED=NO
|
||||
- name: Perform CodeQL Analysis
|
||||
uses: github/codeql-action/analyze@v3
|
||||
with:
|
||||
category: "/language:${{matrix.language}}"
|
||||
66
.github/workflows/nightly.yml
vendored
Normal file
@@ -0,0 +1,66 @@
|
||||
name: Nightly
|
||||
|
||||
on:
|
||||
schedule:
|
||||
- cron: "0 8 * * *"
|
||||
workflow_dispatch:
|
||||
|
||||
jobs:
|
||||
build:
|
||||
runs-on: macos-26
|
||||
permissions:
|
||||
id-token: write
|
||||
contents: write
|
||||
attestations: write
|
||||
actions: read
|
||||
timeout-minutes: 10
|
||||
steps:
|
||||
- uses: actions/checkout@v5
|
||||
- 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_26.0.app
|
||||
- name: Update Build Number
|
||||
env:
|
||||
RUN_ID: ${{ github.run_id }}
|
||||
run: |
|
||||
DATE=$(date "+%Y-%m-%d")
|
||||
sed -i '' -e "s/GITHUB_CI_VERSION/0.0.0_nightly-$DATE/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/Config/Config.xcconfig
|
||||
- name: Build
|
||||
run: xcrun xcodebuild -project Sources/Secretive.xcodeproj -scheme Secretive -configuration Release -archivePath Archive.xcarchive archive
|
||||
- name: Move to Artifact Folder
|
||||
run: mkdir Artifact; cp -r Archive.xcarchive/Products/Applications/Secretive.app Artifact
|
||||
- name: Upload App to Artifacts
|
||||
id: upload
|
||||
uses: actions/upload-artifact@v4
|
||||
with:
|
||||
name: Secretive
|
||||
path: Artifact
|
||||
- name: Download Zipped Artifact
|
||||
id: download
|
||||
env:
|
||||
ZIP_ID: ${{ steps.upload.outputs.artifact-id }}
|
||||
GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }}
|
||||
run: |
|
||||
curl -L -H "Authorization: Bearer $GITHUB_TOKEN" -L \
|
||||
https://api.github.com/repos/maxgoedjen/secretive/actions/artifacts/$ZIP_ID/zip > Secretive.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: Attest
|
||||
id: attest
|
||||
uses: actions/attest-build-provenance@v2
|
||||
with:
|
||||
subject-name: "Secretive.zip"
|
||||
subject-digest: sha256:${{ steps.upload.outputs.artifact-digest }}
|
||||
111
.github/workflows/release.yml
vendored
@@ -6,80 +6,93 @@ on:
|
||||
- '*'
|
||||
jobs:
|
||||
test:
|
||||
runs-on: macOS-latest
|
||||
permissions:
|
||||
contents: read
|
||||
runs-on: macos-26
|
||||
timeout-minutes: 10
|
||||
steps:
|
||||
- uses: actions/checkout@v1
|
||||
- uses: actions/checkout@v5
|
||||
- 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_26.0.app
|
||||
- name: Test
|
||||
run: xcrun xcodebuild test -project Secretive.xcodeproj -scheme Secretive
|
||||
run: xcrun xcodebuild -project Sources/Secretive.xcodeproj -scheme PackageTests test
|
||||
# SPM doesn't seem to pick up on the tests currently?
|
||||
# run: swift test --build-system swiftbuild --package-path Sources/Packages
|
||||
build:
|
||||
runs-on: macOS-latest
|
||||
permissions:
|
||||
id-token: write
|
||||
contents: write
|
||||
attestations: write
|
||||
actions: read
|
||||
runs-on: macos-26
|
||||
timeout-minutes: 10
|
||||
steps:
|
||||
- uses: actions/checkout@v1
|
||||
- name: Create Release
|
||||
id: create_release
|
||||
uses: actions/create-release@v1
|
||||
env:
|
||||
GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }}
|
||||
with:
|
||||
tag_name: ${{ github.ref }}
|
||||
release_name: ${{ github.ref }}
|
||||
body: "Build: https://github.com/maxgoedjen/secretive/actions/runs/${{ github.run_id }}"
|
||||
draft: true
|
||||
prerelease: false
|
||||
- uses: actions/checkout@v5
|
||||
- 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_26.0.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/CI_VERSION = 0.0.0/CI_VERSION = $CLEAN_TAG/g" Config/Config.xcconfig
|
||||
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/github.com\/maxgoedjen\/secretive\/actions\/runs\/$RUN_ID/g" Sources/Config/Config.xcconfig
|
||||
- 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
|
||||
uses: actions/upload-release-asset@v1.0.1
|
||||
env:
|
||||
GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }}
|
||||
with:
|
||||
upload_url: ${{ steps.create_release.outputs.upload_url }}
|
||||
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
|
||||
uses: actions/upload-artifact@v1
|
||||
run: xcrun xcodebuild -project Sources/Secretive.xcodeproj -scheme Secretive -configuration Release -archivePath Archive.xcarchive archive
|
||||
- name: Move to Artifact Folder
|
||||
run: mkdir Artifact; cp -r Archive.xcarchive/Products/Applications/Secretive.app Artifact
|
||||
- name: Upload App to Artifacts
|
||||
id: upload
|
||||
uses: actions/upload-artifact@v4
|
||||
with:
|
||||
name: Secretive.zip
|
||||
path: Secretive.zip
|
||||
path: Artifact
|
||||
- name: Download Zipped Artifact
|
||||
id: download
|
||||
env:
|
||||
ZIP_ID: ${{ steps.upload.outputs.artifact-id }}
|
||||
GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }}
|
||||
run: |
|
||||
curl -L -H "Authorization: Bearer $GITHUB_TOKEN" -L \
|
||||
https://api.github.com/repos/maxgoedjen/secretive/actions/artifacts/$ZIP_ID/zip > Secretive.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: Attest
|
||||
id: attest
|
||||
uses: actions/attest-build-provenance@v2
|
||||
with:
|
||||
subject-path: "Secretive.zip"
|
||||
- name: Create Release
|
||||
env:
|
||||
GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }}
|
||||
TAG_NAME: ${{ github.ref }}
|
||||
RUN_ID: ${{ github.run_id }}
|
||||
ATTESTATION_ID: ${{ steps.attest.outputs.attestation-id }}
|
||||
run: |
|
||||
sed -i.tmp "s/RUN_ID/$RUN_ID/g" .github/templates/release.md
|
||||
sed -i.tmp "s/ATTESTATION_ID/$ATTESTATION_ID/g" .github/templates/release.md
|
||||
gh release create $TAG_NAME -d -F .github/templates/release.md
|
||||
gh release upload $TAG_NAME Secretive.zip
|
||||
|
||||
25
.github/workflows/test.yml
vendored
@@ -1,18 +1,19 @@
|
||||
name: Test
|
||||
|
||||
on: push
|
||||
on: [push, pull_request]
|
||||
jobs:
|
||||
test:
|
||||
runs-on: macOS-latest
|
||||
permissions:
|
||||
contents: read
|
||||
runs-on: macos-26
|
||||
timeout-minutes: 10
|
||||
steps:
|
||||
- uses: actions/checkout@v1
|
||||
- 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: Test
|
||||
run: xcrun xcodebuild test -project Secretive.xcodeproj -scheme Secretive
|
||||
- uses: actions/checkout@v5
|
||||
- name: Set Environment
|
||||
run: sudo xcrun xcode-select -s /Applications/Xcode_26.0.app
|
||||
- name: Test Main Packages
|
||||
run: xcrun xcodebuild -project Sources/Secretive.xcodeproj -scheme PackageTests test
|
||||
# SPM doesn't seem to pick up on the tests currently?
|
||||
# run: swift test --build-system swiftbuild --package-path Sources/Packages
|
||||
- name: Test SecretKit Packages
|
||||
run: swift test --build-system swiftbuild
|
||||
|
||||
2
.gitignore
vendored
@@ -91,3 +91,5 @@ iOSInjectionProject/
|
||||
|
||||
# Build script products
|
||||
Archive.xcarchive
|
||||
.DS_Store
|
||||
contents.xcworkspacedata
|
||||
|
||||
3
APP_CONFIG.md
Normal file
@@ -0,0 +1,3 @@
|
||||
# App Configuration
|
||||
|
||||
Instructions for setting up apps and shells has moved to [secretive-config-instructions](https://github.com/maxgoedjen/secretive-config-instructions)!
|
||||
@@ -8,12 +8,24 @@ Security is obviously paramount for a project like Secretive. As such, any contr
|
||||
|
||||
### Dependencies
|
||||
|
||||
Secretive is desigend to be easily auditable by people who are considering using it. In keeping with this, Secretive has no third party dependencies, and any contributions which bring in new dependencies will be rejected.
|
||||
Secretive is designed to be easily auditable by people who are considering using it. In keeping with this, Secretive has no third party dependencies, and any contributions which bring in new dependencies will be rejected.
|
||||
|
||||
## Code of Conduct
|
||||
|
||||
All contributors must abide by the [Code of Conduct](CODE_OF_CONDUCT.md)
|
||||
|
||||
## Localization
|
||||
|
||||
If you'd like to contribute a translation, please see [Localizing](LOCALIZING.md) to get started.
|
||||
|
||||
## Credits
|
||||
|
||||
If you make a material contribution to the app, please add yourself to the end of the [credits](https://github.com/maxgoedjen/secretive/blob/main/Sources/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 +0,0 @@
|
||||
CI_VERSION = 0.0.0
|
||||
@@ -1,41 +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"
|
||||
}
|
||||
},
|
||||
{
|
||||
"parallelizable" : true,
|
||||
"target" : {
|
||||
"containerPath" : "container:Secretive.xcodeproj",
|
||||
"identifier" : "50617D9323FCE48E0099B055",
|
||||
"name" : "SecretiveTests"
|
||||
}
|
||||
}
|
||||
],
|
||||
"version" : 1
|
||||
}
|
||||
3
Design/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).
|
||||
69
FAQ.md
Normal file
@@ -0,0 +1,69 @@
|
||||
# FAQ
|
||||
|
||||
### How do I import my current SSH keys, or export my Secretive Keys?
|
||||
|
||||
The secure enclave doesn't allow import or export of private keys. For any new computer, you should just create a new set of keys. If you're using a smart card, you _might_ be able to export your private key from the vendor's software.
|
||||
|
||||
### Secretive doesn't work with my git client/app
|
||||
|
||||
Secretive relies on the `SSH_AUTH_SOCK` environment variable being respected. The `git` and `ssh` command line tools natively respect this, but third party apps may require some configuration to work. A non-exhaustive list of setup steps is provided in the [secretive-config-instructions](https://github.com/maxgoedjen/secretive-config-instructions) repo.
|
||||
|
||||
### Secretive isn't working for me
|
||||
|
||||
Please run `ssh -Tv git@github.com` in your terminal and paste the output in a [new GitHub issue](https://github.com/maxgoedjen/secretive/issues/new) with a description of your issue.
|
||||
|
||||
### Secretive was working for me, but now it has stopped
|
||||
|
||||
Try running the "Setup Secretive" process by clicking on "Help", then "Setup Secretive." If that doesn't work, follow the process above.
|
||||
|
||||
### Secretive prompts me to type my password instead of using my Apple Watch
|
||||
|
||||
1) Make sure you have enabled "Use your Apple Watch to unlock apps and your Mac" in System Preferences --> Security & Privacy:
|
||||
|
||||

|
||||
|
||||
2) Ensure that unlocking your Mac with Apple Watch is working (lock and unlock at least once)
|
||||
3) Now you should get prompted on the watch when your key is accessed. Double click the side button to approve:
|
||||
|
||||

|
||||

|
||||
|
||||
### How do I tell SSH to use a specific key?
|
||||
|
||||
Beginning with Secretive 2.2, every secret has an automatically generated public key file representation on disk, and the path to it is listed under "Public Key Path" in Secretive. You can specify that you want to use that key in your `~/.ssh/config`. [This ServerFault answer](https://serverfault.com/a/295771) has more details on setting that up.
|
||||
|
||||
### How can I generate an RSA key?
|
||||
|
||||
The Mac's Secure Enclave only supports 256-bit EC keys, so inherently Secretive cannot support generating RSA keys.
|
||||
|
||||
### Can I use Secretive for SSH Agent Forwarding?
|
||||
|
||||
Yes, you can! Once you've set up Secretive, just add `ForwardAgent yes` to the hosts you want to forward to in your SSH config file. Afterwards, any use of one of your SSH keys on the remote host must be authenticated through Secretive.
|
||||
|
||||
### Why should I trust you?
|
||||
|
||||
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).
|
||||
|
||||
### I want to build Secretive from source
|
||||
|
||||
Awesome! Just bear in mind that because an app only has access to the keychain items that it created, if you have secrets that you created with the prebuilt version of Secretive, you'll be unable to access them using your own custom build (since you'll have changed the bundled ID).
|
||||
|
||||
### 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/Sources/Packages/Sources/Brief/Updater.swift).
|
||||
|
||||
### How do I uninstall Secretive?
|
||||
|
||||
Drag Secretive.app to the trash and remove `~/Library/Containers/com.maxgoedjen.Secretive.SecretAgent`. `SecretAgent` may continue running until you quit it or reboot.
|
||||
|
||||
### I have a security issue
|
||||
|
||||
Please contact [max.goedjen@gmail.com](mailto:max.goedjen@gmail.com) with a subject containing "SECRETIVE SECURITY" immediately with details, and I'll address the issue and credit you ASAP.
|
||||
|
||||
### I have a non-security related bug
|
||||
|
||||
Please file a [GitHub issue](https://github.com/maxgoedjen/secretive/issues/new) for it. I will not provide email support with the exception of the critical security issues mentioned above.
|
||||
|
||||
### I want to contribute to Secretive
|
||||
|
||||
Sweet! Please check out the [contributing guidelines](CONTRIBUTING.md) and go from there.
|
||||
36
LOCALIZING.md
Normal file
@@ -0,0 +1,36 @@
|
||||
# Localizing Secretive
|
||||
|
||||
If you speak another language, and would like to help translate Secretive to support that language, we'd love your help!
|
||||
|
||||
## Crowdin
|
||||
|
||||
[Secretive uses Crowdin for localization](https://crowdin.com/project/secretive/). Open the link and select your language to translate!
|
||||
|
||||
### Manual Translation
|
||||
|
||||
Crowdin is the easiest way to translate Secretive, but I'm happy to accept Pull Requests directly as well.
|
||||
|
||||
### Questions
|
||||
|
||||
Please open an issue if you have a question about translating the app. I'm more than happy to clarify any terms that are ambiguous or confusing. Thanks for contributing!
|
||||
|
||||
### Thank You
|
||||
|
||||
Thanks to all the folks who have contributed localizations so far!
|
||||
|
||||
- @mtardy for the French localization
|
||||
- @GravityRyu for the Chinese localization
|
||||
- @Saeger for the Portuguese (Brazil) localization
|
||||
- @moritzsternemann for the German localization
|
||||
- @RoboRich00A16 for the Italian localization
|
||||
- @akx for the Finnish localization
|
||||
- @mog422 for the Korean localization
|
||||
- @niw for the Japanese localization
|
||||
- @truita for the Catalan localization
|
||||
- @Adimac93 for the Polish localization
|
||||
- @alongotv for the Russian localization
|
||||
|
||||
|
||||
|
||||
|
||||
A special thanks to [Crowdin](https://crowdin.com) for their [generous support of open source projects](https://crowdin.com/page/open-source-project-setup-request).
|
||||
69
Package.swift
Normal file
@@ -0,0 +1,69 @@
|
||||
// swift-tools-version:6.2
|
||||
// The swift-tools-version declares the minimum version of Swift required to build this package.
|
||||
|
||||
import PackageDescription
|
||||
|
||||
// This is basically the same package as `Sources/Packages/Package.swift`, but thinned slightly.
|
||||
// Ideally this would be the same package, but SPM requires it to be at the root of the project,
|
||||
// and Xcode does _not_ like that, so they're separate.
|
||||
let package = Package(
|
||||
name: "SecretKit",
|
||||
defaultLocalization: "en",
|
||||
platforms: [
|
||||
.macOS(.v14)
|
||||
],
|
||||
products: [
|
||||
.library(
|
||||
name: "SecretKit",
|
||||
targets: ["SecretKit"]),
|
||||
.library(
|
||||
name: "SecureEnclaveSecretKit",
|
||||
targets: ["SecureEnclaveSecretKit"]),
|
||||
.library(
|
||||
name: "SmartCardSecretKit",
|
||||
targets: ["SmartCardSecretKit"]),
|
||||
],
|
||||
dependencies: [
|
||||
],
|
||||
targets: [
|
||||
.target(
|
||||
name: "SecretKit",
|
||||
dependencies: [],
|
||||
path: "Sources/Packages/Sources/SecretKit",
|
||||
resources: [localization],
|
||||
swiftSettings: swiftSettings
|
||||
),
|
||||
.testTarget(
|
||||
name: "SecretKitTests",
|
||||
dependencies: ["SecretKit", "SecureEnclaveSecretKit", "SmartCardSecretKit"],
|
||||
path: "Sources/Packages/Tests/SecretKitTests",
|
||||
swiftSettings: swiftSettings
|
||||
),
|
||||
.target(
|
||||
name: "SecureEnclaveSecretKit",
|
||||
dependencies: ["SecretKit"],
|
||||
path: "Sources/Packages/Sources/SecureEnclaveSecretKit",
|
||||
resources: [localization],
|
||||
swiftSettings: swiftSettings
|
||||
),
|
||||
.target(
|
||||
name: "SmartCardSecretKit",
|
||||
dependencies: ["SecretKit"],
|
||||
path: "Sources/Packages/Sources/SmartCardSecretKit",
|
||||
resources: [localization],
|
||||
swiftSettings: swiftSettings
|
||||
),
|
||||
]
|
||||
)
|
||||
|
||||
var localization: Resource {
|
||||
.process("../../Resources/Localizable.xcstrings")
|
||||
}
|
||||
|
||||
var swiftSettings: [PackageDescription.SwiftSetting] {
|
||||
[
|
||||
.swiftLanguageMode(.v6),
|
||||
// This freaks out Xcode in a dependency context.
|
||||
// .treatAllWarnings(as: .error),
|
||||
]
|
||||
}
|
||||
53
README.md
@@ -1,26 +1,31 @@
|
||||
# Secretive
|
||||
# Secretive [](https://github.com/maxgoedjen/secretive/actions/workflows/test.yml) 
|
||||
|
||||
Secretive is an app for storing and managing SSH keys in the Secure Enclave. It is inspired by the [sekey project](https://github.com/sekey/sekey), but rewritten in Swift with no external dependencies and with a handy native management app.
|
||||
|
||||
<img src="/.github/readme/app.png" alt="Screenshot of Secretive" width="600">
|
||||
Secretive is an app for protecting and managing SSH keys with the Secure Enclave.
|
||||
<picture>
|
||||
<source media="(prefers-color-scheme: dark)" srcset="/.github/readme/app-dark.png">
|
||||
<source media="(prefers-color-scheme: light)" srcset="/.github/readme/app-light.png">
|
||||
<img src="/.github/readme/app-dark.png" alt="Screenshot of Secretive" width="600">
|
||||
</picture>
|
||||
|
||||
|
||||
## Why?
|
||||
|
||||
### Safer Storage
|
||||
|
||||
The most common setup for SSH keys is just keeping them on disk, guarded by proper permissions. This is fine in most cases, but it's not super hard for malicious users or malware to copy your private key. If you store your keys in the Secure Enclave, it's impossible to export them, by design.
|
||||
The most common setup for SSH keys is just keeping them on disk, guarded by proper permissions. This is fine in most cases, but it's not super hard for malicious users or malware to copy your private key. If you protect your keys with the Secure Enclave, it's impossible to export them, by design.
|
||||
|
||||
### Access Control
|
||||
|
||||
If your Mac has a Secure Enclave, it also has support for strong biometric access controls like Touch ID. You can configure your key so that they require Touch ID (or Watch) authentication before they're accessed.
|
||||
If your Mac has a Secure Enclave, it also has support for strong access controls like Touch ID, or authentication with Apple Watch. You can configure your keys so that they require Touch ID (or Watch) authentication before they're accessed.
|
||||
|
||||
<img src="/.github/readme/touchid.png" alt="Screenshot of Secretive authenticating with Touch ID">
|
||||
<img src="/.github/readme/touchid.png" alt="Screenshot of Secretive authenticating with Touch ID" width="400">
|
||||
|
||||
### Notifications
|
||||
|
||||
Secretive also notifies you whenever your keys are acceessed, so you're never caught off guard.
|
||||
Secretive also notifies you whenever your keys are accessed, so you're never caught off guard.
|
||||
|
||||
<img src="/.github/readme/notification.png" alt="Screenshot of Secretive notifying the user">
|
||||
<img src="/.github/readme/notification.png" alt="Screenshot of Secretive notifying the user" width="600">
|
||||
|
||||
### Support for Smart Cards Too!
|
||||
|
||||
@@ -28,26 +33,40 @@ For Macs without Secure Enclaves, you can configure a Smart Card (such as a Yubi
|
||||
|
||||
## Getting Started
|
||||
|
||||
### Setup for Third Party Apps
|
||||
### Installation
|
||||
|
||||
When you first launch Secretive, you'll be prompted to set up your command line environment. You can redisplay this prompt at any time by going to `Menu > Help -> Set Up Helper App`.
|
||||
For non-command-line based apps, like GUI Git clients, you may need to go through app-specific setup.
|
||||
#### Direct Download
|
||||
|
||||
[Tower](https://www.git-tower.com/help/mac/integration/environment)
|
||||
You can download the latest release over on the [Releases Page](https://github.com/maxgoedjen/secretive/releases)
|
||||
|
||||
#### Using Homebrew
|
||||
|
||||
### Security Considerations
|
||||
brew install secretive
|
||||
|
||||
Builds are produced by GitHub Actions with an auditable build and release generation process. Each build has a "Document SHAs" step, which will output SHA checksums for the build produced by the GitHub Action, so you can verify that the source code for a given build corresponds to any given release.
|
||||
### FAQ
|
||||
|
||||
There's a [FAQ here](FAQ.md).
|
||||
|
||||
### Auditable Build Process
|
||||
|
||||
Builds are produced by GitHub Actions with an auditable build and release generation process. Starting with Secretive 3.0, builds are attested using [GitHub Artifact Attestation](https://docs.github.com/en/actions/concepts/security/artifact-attestations). Attestations are viewable in the build log for a build, and also on the [main attestation page](https://github.com/maxgoedjen/secretive/attestations).
|
||||
|
||||
### A Note Around Code Signing and Keychains
|
||||
|
||||
While Secretive uses the Secure Enclave for key storage, it still relies on Keychain APIs to access them. Keychain restricts reads of keys to the app (and specifically, the bundle ID) that created them. If you build Secretive from source, make sure you are consistent in which bundle ID you use so that the Keychain is able to locate your keys.
|
||||
While Secretive uses the Secure Enclave to protect keys, it still relies on Keychain APIs to store and access them. Keychain restricts reads of keys to the app (and specifically, the bundle ID) that created them. If you build Secretive from source, make sure you are consistent in which bundle ID you use so that the Keychain is able to locate your keys.
|
||||
|
||||
### Backups and Transfers to New Machines
|
||||
|
||||
Beacuse secrets in the Secure Enclave are not exportable, they are not able to be backed up, and you will not be able to transfer them to a new machine. If you get a new Mac, just create a new set of secrets specific to that Mac.
|
||||
Because secrets in the Secure Enclave are not exportable, they are not able to be backed up, and you will not be able to transfer them to a new machine. If you get a new Mac, just create a new set of secrets specific to that Mac.
|
||||
|
||||
## Security
|
||||
|
||||
If you discover any vulnerabilities in this project, please notify max.goedjen@gmail.com
|
||||
Secretive's security policy is detailed in [SECURITY.md](SECURITY.md). To report security issues, please use [GitHub's private reporting feature.](https://docs.github.com/en/code-security/security-advisories/guidance-on-reporting-and-writing-information-about-vulnerabilities/privately-reporting-a-security-vulnerability#privately-reporting-a-security-vulnerability)
|
||||
|
||||
## Acknowledgements
|
||||
|
||||
### sekey
|
||||
Secretive was inspired by the [sekey project](https://github.com/sekey/sekey).
|
||||
|
||||
### Localization
|
||||
Secretive is localized to many languages by a generous team of volunteers. To learn more, see [LOCALIZING.md](LOCALIZING.md). Secretive's localization workflow is generously provided by [Crowdin](https://crowdin.com).
|
||||
|
||||
27
SECURITY.md
Normal file
@@ -0,0 +1,27 @@
|
||||
# Security Policy
|
||||
|
||||
## Security Principles
|
||||
|
||||
Secretive is designed with a few general tenets in mind:
|
||||
|
||||
### It's Hard to Leak a Key Secretive Can't Read The Key Material
|
||||
|
||||
Secretive only operates on hardware-backed keys. In general terms, this means that it should be _very_ hard for Secretive to have any sort of bug that causes a key to be shared, because Secretive can't access private key data even if it wants to.
|
||||
|
||||
### Simplicity and Auditability
|
||||
|
||||
Secretive won't expand to have every feature it could possibly have. Part of the goal of the app is that it is possible for consumers to reasonably audit the code, and that often means not implementing features that might be cool, but which would significantly inflate the size of the codebase.
|
||||
|
||||
### Dependencies
|
||||
|
||||
Both in support of the previous principle and to rule out supply chain attacks, Secretive does not rely on any third party dependencies.
|
||||
|
||||
There are limited exceptions to this, particularly in the build process, but the app itself does not depend on any third party code.
|
||||
|
||||
## Supported Versions
|
||||
|
||||
The latest version on the [Releases page](https://github.com/maxgoedjen/secretive/releases) is the only currently supported version.
|
||||
|
||||
## Reporting a Vulnerability
|
||||
|
||||
To report security issues, please use [GitHub's private reporting feature.](https://docs.github.com/en/code-security/security-advisories/guidance-on-reporting-and-writing-information-about-vulnerabilities/privately-reporting-a-security-vulnerability#privately-reporting-a-security-vulnerability)
|
||||
@@ -1,150 +0,0 @@
|
||||
import Foundation
|
||||
import CryptoKit
|
||||
import OSLog
|
||||
import SecretKit
|
||||
import SecretAgentKit
|
||||
|
||||
class Agent {
|
||||
|
||||
fileprivate let storeList: SecretStoreList
|
||||
fileprivate let notifier: Notifier
|
||||
|
||||
public init(storeList: SecretStoreList, notifier: Notifier) {
|
||||
os_log(.debug, "Agent is running")
|
||||
self.storeList = storeList
|
||||
self.notifier = notifier
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
extension Agent {
|
||||
|
||||
func handle(fileHandle: FileHandle) {
|
||||
os_log(.debug, "Agent handling new data")
|
||||
let data = fileHandle.availableData
|
||||
guard !data.isEmpty else { return }
|
||||
let requestTypeInt = data[4]
|
||||
guard let requestType = SSHAgent.RequestType(rawValue: requestTypeInt) else { return }
|
||||
os_log(.debug, "Agent handling request of type %@", requestType.debugDescription)
|
||||
let subData = Data(data[5...])
|
||||
handle(requestType: requestType, data: subData, fileHandle: fileHandle)
|
||||
}
|
||||
|
||||
func handle(requestType: SSHAgent.RequestType, data: Data, fileHandle: FileHandle) {
|
||||
var response = Data()
|
||||
do {
|
||||
switch requestType {
|
||||
case .requestIdentities:
|
||||
response.append(SSHAgent.ResponseType.agentIdentitiesAnswer.data)
|
||||
response.append(try identities())
|
||||
os_log(.debug, "Agent returned %@", SSHAgent.ResponseType.agentIdentitiesAnswer.debugDescription)
|
||||
case .signRequest:
|
||||
response.append(SSHAgent.ResponseType.agentSignResponse.data)
|
||||
response.append(try sign(data: data))
|
||||
os_log(.debug, "Agent returned %@", SSHAgent.ResponseType.agentSignResponse.debugDescription)
|
||||
}
|
||||
} catch {
|
||||
response.removeAll()
|
||||
response.append(SSHAgent.ResponseType.agentFailure.data)
|
||||
os_log(.debug, "Agent returned %@", SSHAgent.ResponseType.agentFailure.debugDescription)
|
||||
}
|
||||
let full = OpenSSHKeyWriter().lengthAndData(of: response)
|
||||
fileHandle.write(full)
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
extension Agent {
|
||||
|
||||
func identities() throws -> Data {
|
||||
// TODO: RESTORE ONCE XCODE 11.4 IS GM
|
||||
let secrets = storeList.stores.flatMap { $0.secrets }
|
||||
// let secrets = storeList.stores.flatMap(\.secrets)
|
||||
var count = UInt32(secrets.count).bigEndian
|
||||
let countData = Data(bytes: &count, count: UInt32.bitWidth/8)
|
||||
var keyData = Data()
|
||||
let writer = OpenSSHKeyWriter()
|
||||
for secret in secrets {
|
||||
let keyBlob = writer.data(secret: secret)
|
||||
keyData.append(writer.lengthAndData(of: keyBlob))
|
||||
let curveData = writer.curveType(for: secret.algorithm, length: secret.keySize).data(using: .utf8)!
|
||||
keyData.append(writer.lengthAndData(of: curveData))
|
||||
}
|
||||
os_log(.debug, "Agent enumerated %@ identities", secrets.count as NSNumber)
|
||||
return countData + keyData
|
||||
}
|
||||
|
||||
func sign(data: Data) throws -> Data {
|
||||
let reader = OpenSSHReader(data: data)
|
||||
let writer = OpenSSHKeyWriter()
|
||||
let hash = try reader.readNextChunk()
|
||||
let matching = storeList.stores.compactMap { store -> (AnySecretStore, AnySecret)? in
|
||||
let allMatching = store.secrets.filter { secret in
|
||||
hash == writer.data(secret: secret)
|
||||
}
|
||||
if let matching = allMatching.first {
|
||||
return (store, matching)
|
||||
}
|
||||
return nil
|
||||
}
|
||||
guard let (store, secret) = matching.first else {
|
||||
throw AgentError.noMatchingKey
|
||||
}
|
||||
let dataToSign = try reader.readNextChunk()
|
||||
let derSignature = try store.sign(data: dataToSign, with: secret)
|
||||
// TODO: Move this
|
||||
notifier.notify(accessTo: secret)
|
||||
let curveData = writer.curveType(for: secret.algorithm, length: secret.keySize).data(using: .utf8)!
|
||||
|
||||
// Convert from DER formatted rep to raw (r||s)
|
||||
|
||||
let rawRepresentation: Data
|
||||
switch (secret.algorithm, secret.keySize) {
|
||||
case (.ellipticCurve, 256):
|
||||
rawRepresentation = try CryptoKit.P256.Signing.ECDSASignature(derRepresentation: derSignature).rawRepresentation
|
||||
case (.ellipticCurve, 384):
|
||||
rawRepresentation = try CryptoKit.P384.Signing.ECDSASignature(derRepresentation: derSignature).rawRepresentation
|
||||
default:
|
||||
fatalError()
|
||||
}
|
||||
|
||||
|
||||
let rawLength = rawRepresentation.count/2
|
||||
let r = rawRepresentation[0..<rawLength]
|
||||
let s = rawRepresentation[rawLength...]
|
||||
|
||||
var signatureChunk = Data()
|
||||
signatureChunk.append(writer.lengthAndData(of: r))
|
||||
signatureChunk.append(writer.lengthAndData(of: s))
|
||||
|
||||
var signedData = Data()
|
||||
var sub = Data()
|
||||
sub.append(writer.lengthAndData(of: curveData))
|
||||
sub.append(writer.lengthAndData(of: signatureChunk))
|
||||
signedData.append(writer.lengthAndData(of: sub))
|
||||
|
||||
os_log(.debug, "Agent signed request")
|
||||
|
||||
return signedData
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
|
||||
extension Agent {
|
||||
|
||||
enum AgentError: Error {
|
||||
case unhandledType
|
||||
case noMatchingKey
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
extension SSHAgent.ResponseType {
|
||||
|
||||
var data: Data {
|
||||
var raw = self.rawValue
|
||||
return Data(bytes: &raw, count: UInt8.bitWidth/8)
|
||||
}
|
||||
|
||||
}
|
||||
@@ -1,37 +0,0 @@
|
||||
import Cocoa
|
||||
import SecretKit
|
||||
import OSLog
|
||||
|
||||
@NSApplicationMain
|
||||
class AppDelegate: NSObject, NSApplicationDelegate {
|
||||
|
||||
let storeList: SecretStoreList = {
|
||||
let list = SecretStoreList()
|
||||
list.add(store: SecureEnclave.Store())
|
||||
list.add(store: SmartCard.Store())
|
||||
return list
|
||||
}()
|
||||
let notifier = Notifier()
|
||||
lazy var agent: Agent = {
|
||||
Agent(storeList: storeList, notifier: notifier)
|
||||
}()
|
||||
lazy var socketController: SocketController = {
|
||||
let path = (NSHomeDirectory() as NSString).appendingPathComponent("socket.ssh") as String
|
||||
return SocketController(path: path)
|
||||
}()
|
||||
|
||||
func applicationDidFinishLaunching(_ aNotification: Notification) {
|
||||
os_log(.debug, "SecretAgent finished launching")
|
||||
DispatchQueue.main.async {
|
||||
self.socketController.handler = self.agent.handle(fileHandle:)
|
||||
}
|
||||
notifier.prompt()
|
||||
}
|
||||
|
||||
func applicationWillTerminate(_ aNotification: Notification) {
|
||||
// Insert code here to tear down your application
|
||||
}
|
||||
|
||||
|
||||
}
|
||||
|
||||
@@ -1,60 +0,0 @@
|
||||
{
|
||||
"images" : [
|
||||
{
|
||||
"idiom" : "mac",
|
||||
"scale" : "1x",
|
||||
"size" : "16x16"
|
||||
},
|
||||
{
|
||||
"idiom" : "mac",
|
||||
"scale" : "2x",
|
||||
"size" : "16x16"
|
||||
},
|
||||
{
|
||||
"idiom" : "mac",
|
||||
"scale" : "1x",
|
||||
"size" : "32x32"
|
||||
},
|
||||
{
|
||||
"idiom" : "mac",
|
||||
"scale" : "2x",
|
||||
"size" : "32x32"
|
||||
},
|
||||
{
|
||||
"idiom" : "mac",
|
||||
"scale" : "1x",
|
||||
"size" : "128x128"
|
||||
},
|
||||
{
|
||||
"idiom" : "mac",
|
||||
"scale" : "2x",
|
||||
"size" : "128x128"
|
||||
},
|
||||
{
|
||||
"filename" : "Icon 2@1x.png",
|
||||
"idiom" : "mac",
|
||||
"scale" : "1x",
|
||||
"size" : "256x256"
|
||||
},
|
||||
{
|
||||
"filename" : "Icon 2@2x.png",
|
||||
"idiom" : "mac",
|
||||
"scale" : "2x",
|
||||
"size" : "256x256"
|
||||
},
|
||||
{
|
||||
"idiom" : "mac",
|
||||
"scale" : "1x",
|
||||
"size" : "512x512"
|
||||
},
|
||||
{
|
||||
"idiom" : "mac",
|
||||
"scale" : "2x",
|
||||
"size" : "512x512"
|
||||
}
|
||||
],
|
||||
"info" : {
|
||||
"author" : "xcode",
|
||||
"version" : 1
|
||||
}
|
||||
}
|
||||
|
Before Width: | Height: | Size: 24 KiB |
|
Before Width: | Height: | Size: 66 KiB |
@@ -1,22 +0,0 @@
|
||||
import Foundation
|
||||
import SecretKit
|
||||
import UserNotifications
|
||||
|
||||
class Notifier {
|
||||
|
||||
func prompt() {
|
||||
let notificationCenter = UNUserNotificationCenter.current()
|
||||
notificationCenter.requestAuthorization(options: .alert) { _, _ in
|
||||
}
|
||||
}
|
||||
|
||||
func notify<SecretType: Secret>(accessTo secret: SecretType) {
|
||||
let notificationCenter = UNUserNotificationCenter.current()
|
||||
let notificationContent = UNMutableNotificationContent()
|
||||
notificationContent.title = "Signed Request"
|
||||
notificationContent.body = "\(secret.name) was used to sign a request."
|
||||
let request = UNNotificationRequest(identifier: UUID().uuidString, content: notificationContent, trigger: nil)
|
||||
notificationCenter.add(request, withCompletionHandler: nil)
|
||||
}
|
||||
|
||||
}
|
||||
@@ -1,6 +0,0 @@
|
||||
{
|
||||
"info" : {
|
||||
"author" : "xcode",
|
||||
"version" : 1
|
||||
}
|
||||
}
|
||||
@@ -1,67 +0,0 @@
|
||||
import Foundation
|
||||
import OSLog
|
||||
|
||||
class SocketController {
|
||||
|
||||
fileprivate var fileHandle: FileHandle?
|
||||
fileprivate var port: SocketPort?
|
||||
var handler: ((FileHandle) -> Void)?
|
||||
|
||||
init(path: String) {
|
||||
os_log(.debug, "Socket controller setting up at %@", path)
|
||||
if let _ = try? FileManager.default.removeItem(atPath: path) {
|
||||
os_log(.debug, "Socket controller removed existing socket")
|
||||
}
|
||||
let exists = FileManager.default.fileExists(atPath: path)
|
||||
assert(!exists)
|
||||
os_log(.debug, "Socket controller path is clear")
|
||||
port = socketPort(at: path)
|
||||
configureSocket(at: path)
|
||||
os_log(.debug, "Socket listening at %@", path)
|
||||
}
|
||||
|
||||
func configureSocket(at path: String) {
|
||||
guard let port = port else { return }
|
||||
fileHandle = FileHandle(fileDescriptor: port.socket, closeOnDealloc: true)
|
||||
NotificationCenter.default.addObserver(self, selector: #selector(handleConnectionAccept(notification:)), name: .NSFileHandleConnectionAccepted, object: nil)
|
||||
NotificationCenter.default.addObserver(self, selector: #selector(handleConnectionDataAvailable(notification:)), name: .NSFileHandleDataAvailable, object: nil)
|
||||
fileHandle?.acceptConnectionInBackgroundAndNotify(forModes: [RunLoop.current.currentMode!])
|
||||
}
|
||||
|
||||
func socketPort(at path: String) -> SocketPort {
|
||||
var addr = sockaddr_un()
|
||||
addr.sun_family = sa_family_t(AF_UNIX)
|
||||
|
||||
var len: Int = 0
|
||||
_ = withUnsafeMutablePointer(to: &addr.sun_path.0) { pointer in
|
||||
path.withCString { cstring in
|
||||
len = strlen(cstring)
|
||||
strncpy(pointer, cstring, len)
|
||||
}
|
||||
}
|
||||
addr.sun_len = UInt8(len+2)
|
||||
|
||||
var data: Data!
|
||||
_ = withUnsafePointer(to: &addr) { pointer in
|
||||
data = Data(bytes: pointer, count: MemoryLayout<sockaddr_un>.size)
|
||||
}
|
||||
|
||||
return SocketPort(protocolFamily: AF_UNIX, socketType: SOCK_STREAM, protocol: 0, address: data)!
|
||||
}
|
||||
|
||||
@objc func handleConnectionAccept(notification: Notification) {
|
||||
os_log(.debug, "Socket controller accepted connection")
|
||||
guard let new = notification.userInfo?[NSFileHandleNotificationFileHandleItem] as? FileHandle else { return }
|
||||
handler?(new)
|
||||
new.waitForDataInBackgroundAndNotify()
|
||||
fileHandle?.acceptConnectionInBackgroundAndNotify(forModes: [RunLoop.current.currentMode!])
|
||||
}
|
||||
|
||||
@objc func handleConnectionDataAvailable(notification: Notification) {
|
||||
os_log(.debug, "Socket controller has new data available")
|
||||
guard let new = notification.object as? FileHandle else { return }
|
||||
os_log(.debug, "Socket controller received new file handle")
|
||||
handler?(new)
|
||||
}
|
||||
|
||||
}
|
||||
@@ -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>Copyright © 2020 Max Goedjen. All rights reserved.</string>
|
||||
</dict>
|
||||
</plist>
|
||||
@@ -1,38 +0,0 @@
|
||||
import Foundation
|
||||
|
||||
public enum SSHAgent {}
|
||||
|
||||
extension SSHAgent {
|
||||
|
||||
public enum RequestType: UInt8, CustomDebugStringConvertible {
|
||||
case requestIdentities = 11
|
||||
case signRequest = 13
|
||||
|
||||
public var debugDescription: String {
|
||||
switch self {
|
||||
case .requestIdentities:
|
||||
return "RequestIdentities"
|
||||
default:
|
||||
return "SignRequest"
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
public enum ResponseType: UInt8, CustomDebugStringConvertible {
|
||||
case agentFailure = 5
|
||||
case agentIdentitiesAnswer = 12
|
||||
case agentSignResponse = 14
|
||||
|
||||
public var debugDescription: String {
|
||||
switch self {
|
||||
case .agentFailure:
|
||||
return "AgentFailure"
|
||||
case .agentIdentitiesAnswer:
|
||||
return "AgentIdentitiesAnswer"
|
||||
case .agentSignResponse:
|
||||
return "AgentSignResponse"
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
}
|
||||
@@ -1,19 +0,0 @@
|
||||
//
|
||||
// SecretAgentKit.h
|
||||
// SecretAgentKit
|
||||
//
|
||||
// Created by Max Goedjen on 2/22/20.
|
||||
// Copyright © 2020 Max Goedjen. All rights reserved.
|
||||
//
|
||||
|
||||
#import <Foundation/Foundation.h>
|
||||
|
||||
//! Project version number for SecretAgentKit.
|
||||
FOUNDATION_EXPORT double SecretAgentKitVersionNumber;
|
||||
|
||||
//! Project version string for SecretAgentKit.
|
||||
FOUNDATION_EXPORT const unsigned char SecretAgentKitVersionString[];
|
||||
|
||||
// In this header, you should import all the public headers of your framework using statements like #import <SecretAgentKit/PublicHeader.h>
|
||||
|
||||
|
||||
@@ -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,19 +0,0 @@
|
||||
//
|
||||
// SecretAgentKitTests.swift
|
||||
// SecretAgentKitTests
|
||||
//
|
||||
// Created by Max Goedjen on 2/22/20.
|
||||
// Copyright © 2020 Max Goedjen. All rights reserved.
|
||||
//
|
||||
|
||||
import XCTest
|
||||
@testable import SecretAgentKit
|
||||
|
||||
class SecretAgentKitTests: XCTestCase {
|
||||
|
||||
func testExample() throws {
|
||||
// This is an example of a functional test case.
|
||||
// Use XCTAssert and related functions to verify your tests produce the correct results.
|
||||
}
|
||||
|
||||
}
|
||||
@@ -1,62 +0,0 @@
|
||||
import Foundation
|
||||
|
||||
public struct AnySecret: Secret {
|
||||
|
||||
let base: Any
|
||||
fileprivate let hashable: AnyHashable
|
||||
fileprivate let _id: () -> AnyHashable
|
||||
fileprivate let _name: () -> String
|
||||
fileprivate let _algorithm: () -> Algorithm
|
||||
fileprivate let _keySize: () -> Int
|
||||
fileprivate let _publicKey: () -> Data
|
||||
|
||||
public init<T>(_ secret: T) where T: Secret {
|
||||
if let secret = secret as? AnySecret {
|
||||
base = secret.base
|
||||
hashable = secret.hashable
|
||||
_id = secret._id
|
||||
_name = secret._name
|
||||
_algorithm = secret._algorithm
|
||||
_keySize = secret._keySize
|
||||
_publicKey = secret._publicKey
|
||||
} else {
|
||||
base = secret as Any
|
||||
self.hashable = secret
|
||||
_id = { secret.id as AnyHashable }
|
||||
_name = { secret.name }
|
||||
_algorithm = { secret.algorithm }
|
||||
_keySize = { secret.keySize }
|
||||
_publicKey = { secret.publicKey }
|
||||
}
|
||||
}
|
||||
|
||||
public var id: AnyHashable {
|
||||
_id()
|
||||
}
|
||||
|
||||
public var name: String {
|
||||
_name()
|
||||
}
|
||||
|
||||
public var algorithm: Algorithm {
|
||||
_algorithm()
|
||||
}
|
||||
|
||||
public var keySize: Int {
|
||||
_keySize()
|
||||
}
|
||||
|
||||
public var publicKey: Data {
|
||||
_publicKey()
|
||||
}
|
||||
|
||||
public static func == (lhs: AnySecret, rhs: AnySecret) -> Bool {
|
||||
lhs.hashable == rhs.hashable
|
||||
}
|
||||
|
||||
public func hash(into hasher: inout Hasher) {
|
||||
hashable.hash(into: &hasher)
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
@@ -1,67 +0,0 @@
|
||||
import Foundation
|
||||
import Combine
|
||||
|
||||
public class AnySecretStore: SecretStore {
|
||||
|
||||
let base: Any
|
||||
fileprivate let _isAvailable: () -> Bool
|
||||
fileprivate let _id: () -> UUID
|
||||
fileprivate let _name: () -> String
|
||||
fileprivate let _secrets: () -> [AnySecret]
|
||||
fileprivate let _sign: (Data, AnySecret) throws -> Data
|
||||
fileprivate var sink: AnyCancellable?
|
||||
|
||||
public init<SecretStoreType>(_ secretStore: SecretStoreType) where SecretStoreType: SecretStore {
|
||||
base = secretStore
|
||||
_isAvailable = { secretStore.isAvailable }
|
||||
_name = { secretStore.name }
|
||||
_id = { secretStore.id }
|
||||
_secrets = { secretStore.secrets.map { AnySecret($0) } }
|
||||
_sign = { try secretStore.sign(data: $0, with: $1.base as! SecretStoreType.SecretType) }
|
||||
sink = secretStore.objectWillChange.sink { _ in
|
||||
self.objectWillChange.send()
|
||||
}
|
||||
}
|
||||
|
||||
public var isAvailable: Bool {
|
||||
return _isAvailable()
|
||||
}
|
||||
|
||||
public var id: UUID {
|
||||
return _id()
|
||||
}
|
||||
|
||||
public var name: String {
|
||||
return _name()
|
||||
}
|
||||
|
||||
public var secrets: [AnySecret] {
|
||||
return _secrets()
|
||||
}
|
||||
|
||||
public func sign(data: Data, with secret: AnySecret) throws -> Data {
|
||||
try _sign(data, secret)
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
public class AnySecretStoreModifiable: AnySecretStore, SecretStoreModifiable {
|
||||
|
||||
fileprivate let _create: (String, Bool) throws -> Void
|
||||
fileprivate let _delete: (AnySecret) 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) }
|
||||
super.init(secretStore)
|
||||
}
|
||||
|
||||
public func create(name: String, requiresAuthentication: Bool) throws {
|
||||
try _create(name, requiresAuthentication)
|
||||
}
|
||||
|
||||
public func delete(secret: AnySecret) throws {
|
||||
try _delete(secret)
|
||||
}
|
||||
|
||||
}
|
||||
@@ -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,25 +0,0 @@
|
||||
import Foundation
|
||||
|
||||
public class OpenSSHReader {
|
||||
|
||||
var remaining: Data
|
||||
|
||||
public init(data: Data) {
|
||||
remaining = Data(data)
|
||||
}
|
||||
|
||||
public func readNextChunk() throws -> Data {
|
||||
let lengthRange = 0..<(UInt32.bitWidth/8)
|
||||
let lengthChunk = remaining[lengthRange]
|
||||
remaining.removeSubrange(lengthRange)
|
||||
let littleEndianLength = lengthChunk.withUnsafeBytes { pointer in
|
||||
return pointer.load(as: UInt32.self)
|
||||
}
|
||||
let length = Int(littleEndianLength.bigEndian)
|
||||
let dataRange = 0..<length
|
||||
let ret = Data(remaining[dataRange])
|
||||
remaining.removeSubrange(dataRange)
|
||||
return ret
|
||||
}
|
||||
|
||||
}
|
||||
@@ -1,35 +0,0 @@
|
||||
import Foundation
|
||||
import Combine
|
||||
|
||||
public class SecretStoreList: ObservableObject {
|
||||
|
||||
@Published public var stores: [AnySecretStore] = []
|
||||
@Published public var modifiableStore: AnySecretStoreModifiable?
|
||||
fileprivate var sinks: [AnyCancellable] = []
|
||||
|
||||
public init() {
|
||||
}
|
||||
|
||||
public func add<SecretStoreType: SecretStore>(store: SecretStoreType) {
|
||||
addInternal(store: AnySecretStore(store))
|
||||
}
|
||||
|
||||
public func add<SecretStoreType: SecretStoreModifiable>(store: SecretStoreType) {
|
||||
let modifiable = AnySecretStoreModifiable(modifiable: store)
|
||||
modifiableStore = modifiable
|
||||
addInternal(store: modifiable)
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
extension SecretStoreList {
|
||||
|
||||
fileprivate func addInternal(store: AnySecretStore) {
|
||||
stores.append(store)
|
||||
let sink = store.objectWillChange.sink {
|
||||
self.objectWillChange.send()
|
||||
}
|
||||
sinks.append(sink)
|
||||
}
|
||||
|
||||
}
|
||||
@@ -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>Copyright © 2020 Max Goedjen. All rights reserved.</string>
|
||||
</dict>
|
||||
</plist>
|
||||
@@ -1,21 +0,0 @@
|
||||
public protocol Secret: Identifiable, Hashable {
|
||||
|
||||
var name: String { get }
|
||||
var algorithm: Algorithm { get }
|
||||
var keySize: Int { get }
|
||||
var publicKey: Data { get }
|
||||
|
||||
}
|
||||
|
||||
public enum Algorithm {
|
||||
case ellipticCurve
|
||||
public init(secAttr: NSNumber) {
|
||||
let secAttrString = secAttr.stringValue as CFString
|
||||
switch secAttrString {
|
||||
case kSecAttrKeyTypeEC:
|
||||
self = .ellipticCurve
|
||||
default:
|
||||
fatalError()
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -1,19 +0,0 @@
|
||||
//
|
||||
// SecretKit.h
|
||||
// SecretKit
|
||||
//
|
||||
// Created by Max Goedjen on 2/18/20.
|
||||
// Copyright © 2020 Max Goedjen. All rights reserved.
|
||||
//
|
||||
|
||||
#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,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) 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 +0,0 @@
|
||||
public enum SecureEnclave {}
|
||||
@@ -1,16 +0,0 @@
|
||||
import Foundation
|
||||
import Combine
|
||||
|
||||
extension SecureEnclave {
|
||||
|
||||
public struct Secret: SecretKit.Secret {
|
||||
|
||||
public let id: Data
|
||||
public let name: String
|
||||
public let algorithm = Algorithm.ellipticCurve
|
||||
public let keySize = 256
|
||||
public let publicKey: Data
|
||||
|
||||
}
|
||||
|
||||
}
|
||||
@@ -1,185 +0,0 @@
|
||||
import Foundation
|
||||
import Security
|
||||
import CryptoTokenKit
|
||||
|
||||
extension SecureEnclave {
|
||||
|
||||
public class Store: SecretStoreModifiable {
|
||||
|
||||
public var isAvailable: Bool {
|
||||
// For some reason, as of build time, CryptoKit.SecureEnclave.isAvailable always returns false
|
||||
// error msg "Received error sending GET UNIQUE DEVICE command"
|
||||
// Verify it with TKTokenWatcher manually.
|
||||
TKTokenWatcher().tokenIDs.contains("com.apple.setoken")
|
||||
}
|
||||
public let id = UUID()
|
||||
public let name = NSLocalizedString("Secure Enclave", comment: "Secure Enclave")
|
||||
@Published public fileprivate(set) var secrets: [Secret] = []
|
||||
|
||||
public init() {
|
||||
DistributedNotificationCenter.default().addObserver(forName: .secretStoreUpdated, object: nil, queue: .main) { _ in
|
||||
self.reloadSecrets(notify: false)
|
||||
}
|
||||
loadSecrets()
|
||||
}
|
||||
|
||||
// MARK: Public API
|
||||
|
||||
public func create(name: String, requiresAuthentication: Bool) throws {
|
||||
var accessError: SecurityError?
|
||||
let flags: SecAccessControlCreateFlags
|
||||
if requiresAuthentication {
|
||||
flags = [.privateKeyUsage, .userPresence]
|
||||
} else {
|
||||
flags = .privateKeyUsage
|
||||
}
|
||||
let access =
|
||||
SecAccessControlCreateWithFlags(kCFAllocatorDefault,
|
||||
kSecAttrAccessibleWhenUnlockedThisDeviceOnly,
|
||||
flags,
|
||||
&accessError) as Any
|
||||
if let error = accessError {
|
||||
throw error.takeRetainedValue() as Error
|
||||
}
|
||||
|
||||
let attributes = [
|
||||
kSecAttrLabel: name,
|
||||
kSecAttrKeyType: Constants.keyType,
|
||||
kSecAttrTokenID: kSecAttrTokenIDSecureEnclave,
|
||||
kSecAttrApplicationTag: Constants.keyTag,
|
||||
kSecPrivateKeyAttrs: [
|
||||
kSecAttrIsPermanent: true,
|
||||
kSecAttrAccessControl: access
|
||||
]
|
||||
] 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)
|
||||
}
|
||||
try savePublicKey(pk, name: name)
|
||||
reloadSecrets()
|
||||
}
|
||||
|
||||
public func delete(secret: Secret) throws {
|
||||
let deleteAttributes = [
|
||||
kSecClass: kSecClassKey,
|
||||
kSecAttrApplicationLabel: secret.id as CFData
|
||||
] as CFDictionary
|
||||
let status = SecItemDelete(deleteAttributes)
|
||||
if status != errSecSuccess {
|
||||
throw KeychainError(statusCode: status)
|
||||
}
|
||||
reloadSecrets()
|
||||
}
|
||||
|
||||
public func sign(data: Data, with secret: SecretType) throws -> Data {
|
||||
let attributes = [
|
||||
kSecClass: kSecClassKey,
|
||||
kSecAttrKeyClass: kSecAttrKeyClassPrivate,
|
||||
kSecAttrApplicationLabel: secret.id as CFData,
|
||||
kSecAttrKeyType: Constants.keyType,
|
||||
kSecAttrTokenID: kSecAttrTokenIDSecureEnclave,
|
||||
kSecAttrApplicationTag: Constants.keyTag,
|
||||
kSecReturnRef: true
|
||||
] as CFDictionary
|
||||
var untyped: CFTypeRef?
|
||||
let status = SecItemCopyMatching(attributes, &untyped)
|
||||
if status != errSecSuccess {
|
||||
throw KeychainError(statusCode: status)
|
||||
}
|
||||
guard let untypedSafe = untyped else {
|
||||
throw KeychainError(statusCode: errSecSuccess)
|
||||
}
|
||||
let key = untypedSafe as! SecKey
|
||||
var signError: SecurityError?
|
||||
guard let signature = SecKeyCreateSignature(key, .ecdsaSignatureMessageX962SHA256, data as CFData, &signError) else {
|
||||
throw SigningError(error: signError)
|
||||
}
|
||||
return signature as Data
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
extension SecureEnclave.Store {
|
||||
|
||||
fileprivate func reloadSecrets(notify: Bool = true) {
|
||||
secrets.removeAll()
|
||||
loadSecrets()
|
||||
if notify {
|
||||
DistributedNotificationCenter.default().post(name: .secretStoreUpdated, object: nil)
|
||||
}
|
||||
}
|
||||
|
||||
fileprivate func loadSecrets() {
|
||||
let attributes = [
|
||||
kSecClass: kSecClassKey,
|
||||
kSecAttrKeyType: SecureEnclave.Constants.keyType,
|
||||
kSecAttrApplicationTag: SecureEnclave.Constants.keyTag,
|
||||
kSecAttrKeyClass: kSecAttrKeyClassPublic,
|
||||
kSecReturnRef: true,
|
||||
kSecMatchLimit: kSecMatchLimitAll,
|
||||
kSecReturnAttributes: true
|
||||
] as CFDictionary
|
||||
var untyped: CFTypeRef?
|
||||
SecItemCopyMatching(attributes, &untyped)
|
||||
guard let typed = untyped as? [[CFString: Any]] else { return }
|
||||
let wrapped: [SecureEnclave.Secret] = typed.map {
|
||||
let name = $0[kSecAttrLabel] as? String ?? "Unnamed"
|
||||
let id = $0[kSecAttrApplicationLabel] as! Data
|
||||
let publicKeyRef = $0[kSecValueRef] as! SecKey
|
||||
let publicKeyAttributes = SecKeyCopyAttributes(publicKeyRef) as! [CFString: Any]
|
||||
let publicKey = publicKeyAttributes[kSecValueData] as! Data
|
||||
return SecureEnclave.Secret(id: id, name: name, publicKey: publicKey)
|
||||
}
|
||||
secrets.append(contentsOf: wrapped)
|
||||
}
|
||||
|
||||
fileprivate func savePublicKey(_ publicKey: SecKey, name: String) throws {
|
||||
let attributes = [
|
||||
kSecClass: kSecClassKey,
|
||||
kSecAttrKeyType: SecureEnclave.Constants.keyType,
|
||||
kSecAttrKeyClass: kSecAttrKeyClassPublic,
|
||||
kSecAttrApplicationTag: SecureEnclave.Constants.keyTag,
|
||||
kSecValueRef: publicKey,
|
||||
kSecAttrIsPermanent: true,
|
||||
kSecReturnData: true,
|
||||
kSecAttrLabel: name
|
||||
] as CFDictionary
|
||||
let status = SecItemAdd(attributes, nil)
|
||||
if status != errSecSuccess {
|
||||
throw SecureEnclave.KeychainError(statusCode: status)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
extension SecureEnclave {
|
||||
|
||||
public struct KeychainError: Error {
|
||||
public let statusCode: OSStatus
|
||||
}
|
||||
|
||||
public struct SigningError: Error {
|
||||
public let error: SecurityError?
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
extension SecureEnclave {
|
||||
|
||||
public typealias SecurityError = Unmanaged<CFError>
|
||||
|
||||
}
|
||||
|
||||
extension SecureEnclave {
|
||||
|
||||
enum Constants {
|
||||
fileprivate static let keyTag = "com.maxgoedjen.secretive.secureenclave.key".data(using: .utf8)! as CFData
|
||||
fileprivate static let keyType = kSecAttrKeyTypeECSECPrimeRandom
|
||||
}
|
||||
|
||||
}
|
||||
@@ -1 +0,0 @@
|
||||
public enum SmartCard {}
|
||||
@@ -1,143 +0,0 @@
|
||||
import Foundation
|
||||
import Security
|
||||
import CryptoTokenKit
|
||||
|
||||
// TODO: Might need to split this up into "sub-stores?"
|
||||
// ie, each token has its own Store.
|
||||
extension SmartCard {
|
||||
|
||||
public class Store: SecretStore {
|
||||
|
||||
// TODO: Read actual smart card name, eg "YubiKey 5c"
|
||||
@Published public var isAvailable: Bool = false
|
||||
public let id = UUID()
|
||||
public let name = NSLocalizedString("Smart Card", comment: "Smart Card")
|
||||
@Published public fileprivate(set) var secrets: [Secret] = []
|
||||
fileprivate let watcher = TKTokenWatcher()
|
||||
fileprivate var tokenID: String?
|
||||
|
||||
public init() {
|
||||
tokenID = watcher.tokenIDs.filter { !$0.contains("setoken") }.first
|
||||
watcher.setInsertionHandler { string in
|
||||
guard self.tokenID == nil else { return }
|
||||
guard !string.contains("setoken") else { return }
|
||||
self.tokenID = string
|
||||
self.reloadSecrets()
|
||||
self.watcher.addRemovalHandler(self.smartcardRemoved, forTokenID: string)
|
||||
}
|
||||
if let tokenID = tokenID {
|
||||
self.isAvailable = true
|
||||
self.watcher.addRemovalHandler(self.smartcardRemoved, forTokenID: tokenID)
|
||||
}
|
||||
loadSecrets()
|
||||
}
|
||||
|
||||
// MARK: Public API
|
||||
|
||||
public func create(name: String) throws {
|
||||
fatalError("Keys must be created on the smart card.")
|
||||
}
|
||||
|
||||
public func delete(secret: Secret) throws {
|
||||
fatalError("Keys must be deleted on the smart card.")
|
||||
}
|
||||
|
||||
public func sign(data: Data, with secret: SecretType) throws -> Data {
|
||||
guard let tokenID = tokenID else { fatalError() }
|
||||
let attributes = [
|
||||
kSecClass: kSecClassKey,
|
||||
kSecAttrKeyClass: kSecAttrKeyClassPrivate,
|
||||
kSecAttrApplicationLabel: secret.id as CFData,
|
||||
kSecAttrTokenID: tokenID,
|
||||
kSecReturnRef: true
|
||||
] as CFDictionary
|
||||
var untyped: CFTypeRef?
|
||||
let status = SecItemCopyMatching(attributes, &untyped)
|
||||
if status != errSecSuccess {
|
||||
throw KeychainError(statusCode: status)
|
||||
}
|
||||
guard let untypedSafe = untyped else {
|
||||
throw KeychainError(statusCode: errSecSuccess)
|
||||
}
|
||||
let key = untypedSafe as! SecKey
|
||||
var signError: SecurityError?
|
||||
let signatureAlgorithm: SecKeyAlgorithm
|
||||
switch (secret.algorithm, secret.keySize) {
|
||||
case (.ellipticCurve, 256):
|
||||
signatureAlgorithm = .ecdsaSignatureMessageX962SHA256
|
||||
case (.ellipticCurve, 384):
|
||||
signatureAlgorithm = .ecdsaSignatureMessageX962SHA384
|
||||
default:
|
||||
fatalError()
|
||||
}
|
||||
guard let signature = SecKeyCreateSignature(key, signatureAlgorithm, data as CFData, &signError) else {
|
||||
throw SigningError(error: signError)
|
||||
}
|
||||
return signature as Data
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
extension SmartCard.Store {
|
||||
|
||||
fileprivate func smartcardRemoved(for tokenID: String? = nil) {
|
||||
self.tokenID = nil
|
||||
reloadSecrets()
|
||||
}
|
||||
|
||||
fileprivate func reloadSecrets() {
|
||||
DispatchQueue.main.async {
|
||||
self.isAvailable = self.tokenID != nil
|
||||
self.secrets.removeAll()
|
||||
self.loadSecrets()
|
||||
}
|
||||
}
|
||||
|
||||
fileprivate func loadSecrets() {
|
||||
guard let tokenID = tokenID else { return }
|
||||
let attributes = [
|
||||
kSecClass: kSecClassKey,
|
||||
kSecAttrTokenID: tokenID,
|
||||
kSecAttrKeyType: kSecAttrKeyTypeEC, // Restrict to EC
|
||||
kSecReturnRef: true,
|
||||
kSecMatchLimit: kSecMatchLimitAll,
|
||||
kSecReturnAttributes: true
|
||||
] as CFDictionary
|
||||
var untyped: CFTypeRef?
|
||||
SecItemCopyMatching(attributes, &untyped)
|
||||
guard let typed = untyped as? [[CFString: Any]] else { return }
|
||||
let wrapped: [SmartCard.Secret] = typed.map {
|
||||
let name = $0[kSecAttrLabel] as? String ?? "Unnamed"
|
||||
let tokenID = $0[kSecAttrApplicationLabel] as! Data
|
||||
let algorithm = Algorithm(secAttr: $0[kSecAttrKeyType] as! NSNumber)
|
||||
let keySize = $0[kSecAttrKeySizeInBits] as! Int
|
||||
let publicKeyRef = $0[kSecValueRef] as! SecKey
|
||||
let publicKeySecRef = SecKeyCopyPublicKey(publicKeyRef)!
|
||||
let publicKeyAttributes = SecKeyCopyAttributes(publicKeySecRef) as! [CFString: Any]
|
||||
let publicKey = publicKeyAttributes[kSecValueData] as! Data
|
||||
return SmartCard.Secret(id: tokenID, name: name, algorithm: algorithm, keySize: keySize, publicKey: publicKey)
|
||||
}
|
||||
secrets.append(contentsOf: wrapped)
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
extension SmartCard {
|
||||
|
||||
public struct KeychainError: Error {
|
||||
public let statusCode: OSStatus
|
||||
}
|
||||
|
||||
public struct SigningError: Error {
|
||||
public let error: SecurityError?
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
extension SmartCard {
|
||||
|
||||
public typealias SecurityError = Unmanaged<CFError>
|
||||
|
||||
}
|
||||
@@ -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,27 +0,0 @@
|
||||
//
|
||||
// SecretKitTests.swift
|
||||
// SecretKitTests
|
||||
//
|
||||
// Created by Max Goedjen on 2/18/20.
|
||||
// Copyright © 2020 Max Goedjen. All rights reserved.
|
||||
//
|
||||
|
||||
import XCTest
|
||||
@testable import SecretKit
|
||||
|
||||
class SecretKitTests: XCTestCase {
|
||||
|
||||
override func setUp() {
|
||||
// Put setup code here. This method is called before the invocation of each test method in the class.
|
||||
}
|
||||
|
||||
override func tearDown() {
|
||||
// Put teardown code here. This method is called after the invocation of each test method in the class.
|
||||
}
|
||||
|
||||
func testExample() {
|
||||
// This is an example of a functional test case.
|
||||
// Use XCTAssert and related functions to verify your tests produce the correct results.
|
||||
}
|
||||
|
||||
}
|
||||
@@ -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,99 +0,0 @@
|
||||
import Cocoa
|
||||
import SwiftUI
|
||||
import SecretKit
|
||||
|
||||
@NSApplicationMain
|
||||
class AppDelegate: NSObject, NSApplicationDelegate {
|
||||
|
||||
var window: NSWindow!
|
||||
@IBOutlet var newMenuItem: NSMenuItem!
|
||||
@IBOutlet var toolbar: NSToolbar!
|
||||
let storeList: SecretStoreList = {
|
||||
let list = SecretStoreList()
|
||||
list.add(store: SecureEnclave.Store())
|
||||
list.add(store: SmartCard.Store())
|
||||
return list
|
||||
}()
|
||||
let updater = Updater()
|
||||
let agentStatusChecker = AgentStatusChecker()
|
||||
|
||||
func applicationDidFinishLaunching(_ aNotification: Notification) {
|
||||
let contentView = ContentView(storeList: storeList, updater: updater, agentStatusChecker: agentStatusChecker, runSetupBlock: { self.runSetup(sender: nil) })
|
||||
// Create the window and set the content view.
|
||||
window = NSWindow(
|
||||
contentRect: NSRect(x: 0, y: 0, width: 480, height: 300),
|
||||
styleMask: [.titled, .closable, .miniaturizable, .resizable, .fullSizeContentView],
|
||||
backing: .buffered, defer: false)
|
||||
window.center()
|
||||
window.setFrameAutosaveName("Main Window")
|
||||
window.contentView = NSHostingView(rootView: contentView)
|
||||
window.makeKeyAndOrderFront(nil)
|
||||
window.titleVisibility = .hidden
|
||||
window.toolbar = toolbar
|
||||
window.isReleasedWhenClosed = false
|
||||
if storeList.modifiableStore?.isAvailable ?? false {
|
||||
let plus = NSTitlebarAccessoryViewController()
|
||||
plus.view = NSButton(image: NSImage(named: NSImage.addTemplateName)!, target: self, action: #selector(add(sender:)))
|
||||
plus.layoutAttribute = .right
|
||||
window.addTitlebarAccessoryViewController(plus)
|
||||
newMenuItem.isEnabled = true
|
||||
}
|
||||
runSetupIfNeeded()
|
||||
}
|
||||
|
||||
func applicationDidBecomeActive(_ notification: Notification) {
|
||||
agentStatusChecker.check()
|
||||
}
|
||||
|
||||
func applicationShouldHandleReopen(_ sender: NSApplication, hasVisibleWindows flag: Bool) -> Bool {
|
||||
guard !flag else { return false }
|
||||
window.makeKeyAndOrderFront(self)
|
||||
return true
|
||||
}
|
||||
|
||||
@IBAction func add(sender: AnyObject?) {
|
||||
var addWindow: NSWindow!
|
||||
let addView = CreateSecretView(store: storeList.modifiableStore!) {
|
||||
self.window.endSheet(addWindow)
|
||||
}
|
||||
addWindow = NSWindow(
|
||||
contentRect: NSRect(x: 0, y: 0, width: 480, height: 300),
|
||||
styleMask: [.titled, .closable, .miniaturizable, .resizable, .fullSizeContentView],
|
||||
backing: .buffered, defer: false)
|
||||
addWindow.contentView = NSHostingView(rootView: addView)
|
||||
window.beginSheet(addWindow, completionHandler: nil)
|
||||
}
|
||||
|
||||
@IBAction func runSetup(sender: AnyObject?) {
|
||||
let setupWindow = NSWindow(
|
||||
contentRect: NSRect(x: 0, y: 0, width: 480, height: 300),
|
||||
styleMask: [.titled, .closable, .miniaturizable, .resizable, .fullSizeContentView],
|
||||
backing: .buffered, defer: false)
|
||||
let setupView = SetupView() { success in
|
||||
self.window.endSheet(setupWindow)
|
||||
self.agentStatusChecker.check()
|
||||
}
|
||||
setupWindow.contentView = NSHostingView(rootView: setupView)
|
||||
window.beginSheet(setupWindow, completionHandler: nil)
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
extension AppDelegate {
|
||||
|
||||
func runSetupIfNeeded() {
|
||||
if !UserDefaults.standard.bool(forKey: Constants.defaultsHasRunSetup) {
|
||||
UserDefaults.standard.set(true, forKey: Constants.defaultsHasRunSetup)
|
||||
runSetup(sender: nil)
|
||||
}
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
extension AppDelegate {
|
||||
|
||||
enum Constants {
|
||||
static let defaultsHasRunSetup = "defaultsHasRunSetup"
|
||||
}
|
||||
|
||||
}
|
||||
@@ -1,60 +0,0 @@
|
||||
{
|
||||
"images" : [
|
||||
{
|
||||
"idiom" : "mac",
|
||||
"scale" : "1x",
|
||||
"size" : "16x16"
|
||||
},
|
||||
{
|
||||
"idiom" : "mac",
|
||||
"scale" : "2x",
|
||||
"size" : "16x16"
|
||||
},
|
||||
{
|
||||
"idiom" : "mac",
|
||||
"scale" : "1x",
|
||||
"size" : "32x32"
|
||||
},
|
||||
{
|
||||
"idiom" : "mac",
|
||||
"scale" : "2x",
|
||||
"size" : "32x32"
|
||||
},
|
||||
{
|
||||
"idiom" : "mac",
|
||||
"scale" : "1x",
|
||||
"size" : "128x128"
|
||||
},
|
||||
{
|
||||
"idiom" : "mac",
|
||||
"scale" : "2x",
|
||||
"size" : "128x128"
|
||||
},
|
||||
{
|
||||
"filename" : "Icon 2@1x.png",
|
||||
"idiom" : "mac",
|
||||
"scale" : "1x",
|
||||
"size" : "256x256"
|
||||
},
|
||||
{
|
||||
"filename" : "Icon 2@2x.png",
|
||||
"idiom" : "mac",
|
||||
"scale" : "2x",
|
||||
"size" : "256x256"
|
||||
},
|
||||
{
|
||||
"idiom" : "mac",
|
||||
"scale" : "1x",
|
||||
"size" : "512x512"
|
||||
},
|
||||
{
|
||||
"idiom" : "mac",
|
||||
"scale" : "2x",
|
||||
"size" : "512x512"
|
||||
}
|
||||
],
|
||||
"info" : {
|
||||
"author" : "xcode",
|
||||
"version" : 1
|
||||
}
|
||||
}
|
||||
|
Before Width: | Height: | Size: 24 KiB |
|
Before Width: | Height: | Size: 66 KiB |
@@ -1,160 +0,0 @@
|
||||
<?xml version="1.0" encoding="UTF-8"?>
|
||||
<document type="com.apple.InterfaceBuilder3.Cocoa.Storyboard.XIB" version="3.0" toolsVersion="16085" targetRuntime="MacOSX.Cocoa" propertyAccessControl="none" useAutolayout="YES">
|
||||
<dependencies>
|
||||
<plugIn identifier="com.apple.InterfaceBuilder.CocoaPlugin" version="16085"/>
|
||||
<capability name="documents saved in the Xcode 8 format" minToolsVersion="8.0"/>
|
||||
</dependencies>
|
||||
<scenes>
|
||||
<!--Application-->
|
||||
<scene sceneID="JPo-4y-FX3">
|
||||
<objects>
|
||||
<application id="hnw-xV-0zn" sceneMemberID="viewController">
|
||||
<menu key="mainMenu" title="Main Menu" systemMenu="main" autoenablesItems="NO" id="AYu-sK-qS6">
|
||||
<items>
|
||||
<menuItem title="Secretive" id="1Xt-HY-uBw">
|
||||
<modifierMask key="keyEquivalentModifierMask"/>
|
||||
<menu key="submenu" title="Secretive" systemMenu="apple" id="uQy-DD-JDr">
|
||||
<items>
|
||||
<menuItem title="About Secretive" id="5kV-Vb-QxS">
|
||||
<modifierMask key="keyEquivalentModifierMask"/>
|
||||
<connections>
|
||||
<action selector="orderFrontStandardAboutPanel:" target="Ady-hI-5gd" id="Exp-CZ-Vem"/>
|
||||
</connections>
|
||||
</menuItem>
|
||||
<menuItem isSeparatorItem="YES" id="VOq-y0-SEH"/>
|
||||
<menuItem title="Preferences…" keyEquivalent="," id="BOF-NM-1cW"/>
|
||||
<menuItem isSeparatorItem="YES" id="wFC-TO-SCJ"/>
|
||||
<menuItem title="Services" id="NMo-om-nkz">
|
||||
<modifierMask key="keyEquivalentModifierMask"/>
|
||||
<menu key="submenu" title="Services" systemMenu="services" id="hz9-B4-Xy5"/>
|
||||
</menuItem>
|
||||
<menuItem isSeparatorItem="YES" id="4je-JR-u6R"/>
|
||||
<menuItem title="Hide Secretive" keyEquivalent="h" id="Olw-nP-bQN">
|
||||
<connections>
|
||||
<action selector="hide:" target="Ady-hI-5gd" id="PnN-Uc-m68"/>
|
||||
</connections>
|
||||
</menuItem>
|
||||
<menuItem title="Hide Others" keyEquivalent="h" id="Vdr-fp-XzO">
|
||||
<modifierMask key="keyEquivalentModifierMask" option="YES" command="YES"/>
|
||||
<connections>
|
||||
<action selector="hideOtherApplications:" target="Ady-hI-5gd" id="VT4-aY-XCT"/>
|
||||
</connections>
|
||||
</menuItem>
|
||||
<menuItem title="Show All" id="Kd2-mp-pUS">
|
||||
<modifierMask key="keyEquivalentModifierMask"/>
|
||||
<connections>
|
||||
<action selector="unhideAllApplications:" target="Ady-hI-5gd" id="Dhg-Le-xox"/>
|
||||
</connections>
|
||||
</menuItem>
|
||||
<menuItem isSeparatorItem="YES" id="kCx-OE-vgT"/>
|
||||
<menuItem title="Quit Secretive" keyEquivalent="q" id="4sb-4s-VLi">
|
||||
<connections>
|
||||
<action selector="terminate:" target="Ady-hI-5gd" id="Te7-pn-YzF"/>
|
||||
</connections>
|
||||
</menuItem>
|
||||
</items>
|
||||
</menu>
|
||||
</menuItem>
|
||||
<menuItem title="File" id="dMs-cI-mzQ">
|
||||
<modifierMask key="keyEquivalentModifierMask"/>
|
||||
<menu key="submenu" title="File" autoenablesItems="NO" id="bib-Uj-vzu">
|
||||
<items>
|
||||
<menuItem title="New" enabled="NO" keyEquivalent="n" id="Was-JA-tGl">
|
||||
<connections>
|
||||
<action selector="addWithSender:" target="Voe-Tx-rLC" id="U1t-YZ-Hn5"/>
|
||||
</connections>
|
||||
</menuItem>
|
||||
<menuItem isSeparatorItem="YES" id="m54-Is-iLE"/>
|
||||
<menuItem title="Close" keyEquivalent="w" id="DVo-aG-piG">
|
||||
<connections>
|
||||
<action selector="performClose:" target="Ady-hI-5gd" id="HmO-Ls-i7Q"/>
|
||||
</connections>
|
||||
</menuItem>
|
||||
</items>
|
||||
</menu>
|
||||
</menuItem>
|
||||
<menuItem title="Window" id="aUF-d1-5bR">
|
||||
<modifierMask key="keyEquivalentModifierMask"/>
|
||||
<menu key="submenu" title="Window" systemMenu="window" id="Td7-aD-5lo">
|
||||
<items>
|
||||
<menuItem title="Minimize" keyEquivalent="m" id="OY7-WF-poV">
|
||||
<connections>
|
||||
<action selector="performMiniaturize:" target="Ady-hI-5gd" id="VwT-WD-YPe"/>
|
||||
</connections>
|
||||
</menuItem>
|
||||
<menuItem title="Zoom" id="R4o-n2-Eq4">
|
||||
<modifierMask key="keyEquivalentModifierMask"/>
|
||||
<connections>
|
||||
<action selector="performZoom:" target="Ady-hI-5gd" id="DIl-cC-cCs"/>
|
||||
</connections>
|
||||
</menuItem>
|
||||
<menuItem isSeparatorItem="YES" id="eu3-7i-yIM"/>
|
||||
<menuItem title="Bring All to Front" id="LE2-aR-0XJ">
|
||||
<modifierMask key="keyEquivalentModifierMask"/>
|
||||
<connections>
|
||||
<action selector="arrangeInFront:" target="Ady-hI-5gd" id="DRN-fu-gQh"/>
|
||||
</connections>
|
||||
</menuItem>
|
||||
</items>
|
||||
</menu>
|
||||
</menuItem>
|
||||
<menuItem title="Help" id="wpr-3q-Mcd">
|
||||
<modifierMask key="keyEquivalentModifierMask"/>
|
||||
<menu key="submenu" title="Help" systemMenu="help" id="F2S-fz-NVQ">
|
||||
<items>
|
||||
<menuItem title="Setup Helper App" id="04y-R6-7bF">
|
||||
<modifierMask key="keyEquivalentModifierMask"/>
|
||||
<connections>
|
||||
<action selector="runSetupWithSender:" target="Voe-Tx-rLC" id="Fty-2m-eng"/>
|
||||
</connections>
|
||||
</menuItem>
|
||||
<menuItem isSeparatorItem="YES" id="Ddf-5M-Bmf"/>
|
||||
<menuItem title="Secretive Help" keyEquivalent="?" id="FKE-Sm-Kum">
|
||||
<connections>
|
||||
<action selector="showHelp:" target="Ady-hI-5gd" id="y7X-2Q-9no"/>
|
||||
</connections>
|
||||
</menuItem>
|
||||
</items>
|
||||
</menu>
|
||||
</menuItem>
|
||||
</items>
|
||||
</menu>
|
||||
<connections>
|
||||
<outlet property="delegate" destination="Voe-Tx-rLC" id="PrD-fu-P6m"/>
|
||||
</connections>
|
||||
</application>
|
||||
<customObject id="Voe-Tx-rLC" customClass="AppDelegate" customModule="Secretive" customModuleProvider="target">
|
||||
<connections>
|
||||
<outlet property="newMenuItem" destination="Was-JA-tGl" id="C8s-uk-gMA"/>
|
||||
<outlet property="toolbar" destination="bvo-mt-QR4" id="XSF-g2-znt"/>
|
||||
</connections>
|
||||
</customObject>
|
||||
<toolbar implicitIdentifier="09D11707-F4A3-4FD5-970E-AC5832E91C2B" autosavesConfiguration="NO" displayMode="iconAndLabel" sizeMode="regular" id="bvo-mt-QR4">
|
||||
<allowedToolbarItems>
|
||||
<toolbarItem implicitItemIdentifier="NSToolbarFlexibleSpaceItem" id="9Xm-OQ-a7h"/>
|
||||
<toolbarItem implicitItemIdentifier="728E7E6E-F692-41A1-9439-C6EF9BE96CBA" label="Secretive" paletteLabel="" sizingBehavior="auto" id="xbD-W8-Ypr">
|
||||
<nil key="toolTip"/>
|
||||
<textField key="view" horizontalHuggingPriority="251" verticalHuggingPriority="750" id="Mg0-Hm-7bW">
|
||||
<rect key="frame" x="0.0" y="14" width="65" height="16"/>
|
||||
<autoresizingMask key="autoresizingMask" flexibleMaxX="YES" flexibleMinY="YES"/>
|
||||
<textFieldCell key="cell" lineBreakMode="clipping" title="Secretive" id="EXw-BM-zF7">
|
||||
<font key="font" usesAppearanceFont="YES"/>
|
||||
<color key="textColor" name="windowFrameTextColor" catalog="System" colorSpace="catalog"/>
|
||||
<color key="backgroundColor" name="textBackgroundColor" catalog="System" colorSpace="catalog"/>
|
||||
</textFieldCell>
|
||||
</textField>
|
||||
</toolbarItem>
|
||||
</allowedToolbarItems>
|
||||
<defaultToolbarItems>
|
||||
<toolbarItem reference="9Xm-OQ-a7h"/>
|
||||
<toolbarItem reference="xbD-W8-Ypr"/>
|
||||
<toolbarItem reference="9Xm-OQ-a7h"/>
|
||||
</defaultToolbarItems>
|
||||
</toolbar>
|
||||
<customObject id="YLy-65-1bz" customClass="NSFontManager"/>
|
||||
<customObject id="Ady-hI-5gd" userLabel="First Responder" customClass="NSResponder" sceneMemberID="firstResponder"/>
|
||||
</objects>
|
||||
<point key="canvasLocation" x="75" y="0.0"/>
|
||||
</scene>
|
||||
</scenes>
|
||||
</document>
|
||||
@@ -1,33 +0,0 @@
|
||||
import Foundation
|
||||
import Combine
|
||||
import AppKit
|
||||
|
||||
protocol AgentStatusCheckerProtocol: ObservableObject {
|
||||
var running: Bool { get }
|
||||
}
|
||||
|
||||
class AgentStatusChecker: ObservableObject, AgentStatusCheckerProtocol {
|
||||
|
||||
@Published var running: Bool = false
|
||||
|
||||
init() {
|
||||
check()
|
||||
}
|
||||
|
||||
func check() {
|
||||
running = secretAgentProcess != nil
|
||||
}
|
||||
|
||||
var secretAgentProcess: NSRunningApplication? {
|
||||
NSRunningApplication.runningApplications(withBundleIdentifier: Constants.secretAgentAppID).first
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
extension AgentStatusChecker {
|
||||
|
||||
enum Constants {
|
||||
static let secretAgentAppID = "com.maxgoedjen.Secretive.SecretAgent"
|
||||
}
|
||||
|
||||
}
|
||||
@@ -1,82 +0,0 @@
|
||||
import Foundation
|
||||
import Combine
|
||||
|
||||
protocol UpdaterProtocol: ObservableObject {
|
||||
|
||||
var update: Release? { get }
|
||||
|
||||
}
|
||||
|
||||
class Updater: ObservableObject, UpdaterProtocol {
|
||||
|
||||
@Published var update: Release?
|
||||
|
||||
init() {
|
||||
checkForUpdates()
|
||||
let timer = Timer.scheduledTimer(withTimeInterval: 60*60*24, repeats: true) { _ in
|
||||
self.checkForUpdates()
|
||||
}
|
||||
timer.tolerance = 60*60
|
||||
}
|
||||
|
||||
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()
|
||||
}
|
||||
|
||||
func evaluate(release: Release) {
|
||||
let latestVersion = semVer(from: release.name)
|
||||
let currentVersion = semVer(from: Bundle.main.infoDictionary!["CFBundleShortVersionString"] as! String)
|
||||
for (latest, current) in zip(latestVersion, currentVersion) {
|
||||
if latest > current {
|
||||
DispatchQueue.main.async {
|
||||
self.update = release
|
||||
}
|
||||
return
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func semVer(from stringVersion: String) -> [Int] {
|
||||
var split = stringVersion.split(separator: ".").compactMap { Int($0) }
|
||||
while split.count < 3 {
|
||||
split.append(0)
|
||||
}
|
||||
return split
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
extension Updater {
|
||||
|
||||
enum Constants {
|
||||
static let updateURL = URL(string: "https://api.github.com/repos/maxgoedjen/secretive/releases/latest")!
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
struct Release: Codable {
|
||||
let name: String
|
||||
let html_url: URL
|
||||
let body: String
|
||||
}
|
||||
|
||||
|
||||
extension Release {
|
||||
|
||||
var critical: Bool {
|
||||
return body.contains(Constants.securityContent)
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
extension Release {
|
||||
|
||||
enum Constants {
|
||||
static let securityContent = "Critical Security Update"
|
||||
}
|
||||
|
||||
}
|
||||
@@ -1,6 +0,0 @@
|
||||
{
|
||||
"info" : {
|
||||
"version" : 1,
|
||||
"author" : "xcode"
|
||||
}
|
||||
}
|
||||
@@ -1,12 +0,0 @@
|
||||
import Foundation
|
||||
import Combine
|
||||
|
||||
class PreviewAgentStatusChecker: AgentStatusCheckerProtocol {
|
||||
|
||||
let running: Bool
|
||||
|
||||
init(running: Bool = true) {
|
||||
self.running = running
|
||||
}
|
||||
|
||||
}
|
||||
@@ -1,70 +0,0 @@
|
||||
import Foundation
|
||||
import SecretKit
|
||||
|
||||
enum Preview {}
|
||||
|
||||
extension Preview {
|
||||
|
||||
struct Secret: SecretKit.Secret {
|
||||
|
||||
let id = UUID().uuidString
|
||||
let name: String
|
||||
let algorithm = Algorithm.ellipticCurve
|
||||
let keySize = 256
|
||||
let publicKey = UUID().uuidString.data(using: .utf8)!
|
||||
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
extension Preview {
|
||||
|
||||
class Store: SecretStore, ObservableObject {
|
||||
|
||||
let isAvailable = true
|
||||
let id = UUID()
|
||||
var name: String { "Preview Store" }
|
||||
@Published var secrets: [Secret] = []
|
||||
|
||||
init(secrets: [Secret]) {
|
||||
self.secrets.append(contentsOf: secrets)
|
||||
}
|
||||
|
||||
init(numberOfRandomSecrets: Int = 5) {
|
||||
let new = (0..<numberOfRandomSecrets).map { Secret(name: String(describing: $0)) }
|
||||
self.secrets.append(contentsOf: new)
|
||||
}
|
||||
|
||||
func sign(data: Data, with secret: Preview.Secret) throws -> Data {
|
||||
return data
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
class StoreModifiable: Store, SecretStoreModifiable {
|
||||
|
||||
override var name: String { "Modifiable Preview Store" }
|
||||
|
||||
func create(name: String, requiresAuthentication: Bool) throws {
|
||||
}
|
||||
|
||||
func delete(secret: Preview.Secret) throws {
|
||||
}
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
extension Preview {
|
||||
|
||||
static func storeList(stores: [Store] = [], modifiableStores: [StoreModifiable] = []) -> SecretStoreList {
|
||||
let list = SecretStoreList()
|
||||
for store in stores {
|
||||
list.add(store: store)
|
||||
}
|
||||
for storeModifiable in modifiableStores {
|
||||
list.add(store: storeModifiable)
|
||||
}
|
||||
return list
|
||||
}
|
||||
|
||||
}
|
||||
@@ -1,27 +0,0 @@
|
||||
import Foundation
|
||||
import Combine
|
||||
|
||||
class PreviewUpdater: UpdaterProtocol {
|
||||
|
||||
let update: Release?
|
||||
|
||||
init(update: Update = .none) {
|
||||
switch update {
|
||||
case .none:
|
||||
self.update = nil
|
||||
case .advisory:
|
||||
self.update = Release(name: "10.10.10", html_url: URL(string: "https://example.com")!, body: "Some regular update")
|
||||
case .critical:
|
||||
self.update = Release(name: "10.10.10", html_url: URL(string: "https://example.com")!, body: "Critical Security Update")
|
||||
}
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
extension PreviewUpdater {
|
||||
|
||||
enum Update {
|
||||
case none, advisory, critical
|
||||
}
|
||||
|
||||
}
|
||||
@@ -1,144 +0,0 @@
|
||||
import SwiftUI
|
||||
import SecretKit
|
||||
|
||||
struct ContentView<UpdaterType: UpdaterProtocol, AgentStatusCheckerType: AgentStatusCheckerProtocol>: View {
|
||||
|
||||
@ObservedObject var storeList: SecretStoreList
|
||||
@ObservedObject var updater: UpdaterType
|
||||
@ObservedObject var agentStatusChecker: AgentStatusCheckerType
|
||||
var runSetupBlock: (() -> Void)?
|
||||
|
||||
@State fileprivate var active: AnySecret.ID?
|
||||
@State fileprivate var showingDeletion = false
|
||||
@State fileprivate var deletingSecret: AnySecret?
|
||||
|
||||
var body: some View {
|
||||
VStack {
|
||||
if updater.update != nil {
|
||||
updateNotice()
|
||||
}
|
||||
if !agentStatusChecker.running {
|
||||
agentNotice()
|
||||
}
|
||||
NavigationView {
|
||||
List(selection: $active) {
|
||||
ForEach(storeList.stores) { store in
|
||||
if store.isAvailable {
|
||||
Section(header: Text(store.name)) {
|
||||
if store.secrets.isEmpty {
|
||||
if store is AnySecretStoreModifiable {
|
||||
NavigationLink(destination: EmptyStoreModifiableView(), tag: Constants.emptyStoreModifiableTag, selection: self.$active) {
|
||||
Text("No Secrets")
|
||||
}
|
||||
} else {
|
||||
NavigationLink(destination: EmptyStoreView(), tag: Constants.emptyStoreTag, selection: self.$active) {
|
||||
Text("No Secrets")
|
||||
}
|
||||
}
|
||||
} else {
|
||||
ForEach(store.secrets) { secret in
|
||||
NavigationLink(destination: SecretDetailView(secret: secret), tag: secret.id, selection: self.$active) {
|
||||
Text(secret.name)
|
||||
}.contextMenu {
|
||||
if store is AnySecretStoreModifiable {
|
||||
Button(action: { self.delete(secret: secret) }) {
|
||||
Text("Delete")
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}.onAppear {
|
||||
self.active = self.nextDefaultSecret
|
||||
}
|
||||
.listStyle(SidebarListStyle())
|
||||
.frame(minWidth: 100, idealWidth: 240)
|
||||
}
|
||||
.navigationViewStyle(DoubleColumnNavigationViewStyle())
|
||||
.sheet(isPresented: $showingDeletion) {
|
||||
if self.storeList.modifiableStore != nil {
|
||||
DeleteSecretView(secret: self.deletingSecret!, store: self.storeList.modifiableStore!) { deleted in
|
||||
self.showingDeletion = false
|
||||
if deleted {
|
||||
self.active = self.nextDefaultSecret
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func updateNotice() -> some View {
|
||||
guard let update = updater.update else { return AnyView(Spacer()) }
|
||||
let severity: NoticeView.Severity
|
||||
let text: String
|
||||
if update.critical {
|
||||
severity = .critical
|
||||
text = "Critical Security Update Required"
|
||||
} else {
|
||||
severity = .advisory
|
||||
text = "Update Available"
|
||||
}
|
||||
return AnyView(NoticeView(text: text, severity: severity, actionTitle: "Update") {
|
||||
NSWorkspace.shared.open(update.html_url)
|
||||
})
|
||||
}
|
||||
|
||||
func agentNotice() -> some View {
|
||||
NoticeView(text: "Secret Agent isn't running. Run setup again to fix.", severity: .advisory, actionTitle: "Run Setup") {
|
||||
self.runSetupBlock?()
|
||||
}
|
||||
}
|
||||
|
||||
func delete<SecretType: Secret>(secret: SecretType) {
|
||||
deletingSecret = AnySecret(secret)
|
||||
self.showingDeletion = true
|
||||
}
|
||||
|
||||
var nextDefaultSecret: AnyHashable? {
|
||||
let fallback: AnyHashable
|
||||
if self.storeList.modifiableStore?.isAvailable ?? false {
|
||||
fallback = Constants.emptyStoreModifiableTag
|
||||
} else {
|
||||
fallback = Constants.emptyStoreTag
|
||||
}
|
||||
return self.storeList.stores.compactMap { $0.secrets.first }.first?.id ?? fallback
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
fileprivate enum Constants {
|
||||
static let emptyStoreModifiableTag: AnyHashable = "emptyStoreModifiableTag"
|
||||
static let emptyStoreTag: AnyHashable = "emptyStoreModifiableTag"
|
||||
}
|
||||
|
||||
|
||||
#if DEBUG
|
||||
|
||||
struct ContentView_Previews: PreviewProvider {
|
||||
static var previews: some View {
|
||||
Group {
|
||||
ContentView(storeList: Preview.storeList(stores: [Preview.Store(numberOfRandomSecrets: 0)],
|
||||
modifiableStores: [Preview.StoreModifiable(numberOfRandomSecrets: 0)]),
|
||||
updater: PreviewUpdater(),
|
||||
agentStatusChecker: PreviewAgentStatusChecker())
|
||||
ContentView(storeList: Preview.storeList(stores: [Preview.Store()], modifiableStores: [Preview.StoreModifiable()]), updater: PreviewUpdater(),
|
||||
agentStatusChecker: PreviewAgentStatusChecker())
|
||||
ContentView(storeList: Preview.storeList(stores: [Preview.Store()]), updater: PreviewUpdater(),
|
||||
agentStatusChecker: PreviewAgentStatusChecker())
|
||||
ContentView(storeList: Preview.storeList(modifiableStores: [Preview.StoreModifiable()]), updater: PreviewUpdater(),
|
||||
agentStatusChecker: PreviewAgentStatusChecker())
|
||||
ContentView(storeList: Preview.storeList(stores: [Preview.Store(numberOfRandomSecrets: 0)], modifiableStores: [Preview.StoreModifiable(numberOfRandomSecrets: 0)]), updater: PreviewUpdater(update: .advisory),
|
||||
agentStatusChecker: PreviewAgentStatusChecker())
|
||||
ContentView(storeList: Preview.storeList(stores: [Preview.Store(numberOfRandomSecrets: 0)], modifiableStores: [Preview.StoreModifiable(numberOfRandomSecrets: 0)]), updater: PreviewUpdater(update: .critical),
|
||||
agentStatusChecker: PreviewAgentStatusChecker())
|
||||
ContentView(storeList: Preview.storeList(stores: [Preview.Store(numberOfRandomSecrets: 0)], modifiableStores: [Preview.StoreModifiable(numberOfRandomSecrets: 0)]), updater: PreviewUpdater(update: .critical),
|
||||
agentStatusChecker: PreviewAgentStatusChecker(running: false))
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#endif
|
||||
@@ -1,54 +0,0 @@
|
||||
import SwiftUI
|
||||
import SecretKit
|
||||
|
||||
struct CreateSecretView: View {
|
||||
|
||||
@ObservedObject var store: AnySecretStoreModifiable
|
||||
|
||||
@State var name = ""
|
||||
@State var requiresAuthentication = true
|
||||
|
||||
var dismissalBlock: () -> ()
|
||||
|
||||
var body: some View {
|
||||
VStack {
|
||||
HStack {
|
||||
Image(nsImage: NSApp.applicationIconImage)
|
||||
.resizable()
|
||||
.frame(width: 64, height: 64)
|
||||
.padding()
|
||||
VStack {
|
||||
HStack {
|
||||
Text("Create a New Secret").bold()
|
||||
Spacer()
|
||||
}
|
||||
HStack {
|
||||
Text("Name:")
|
||||
TextField("Shhhhh", text: $name)
|
||||
}
|
||||
HStack {
|
||||
Toggle(isOn: $requiresAuthentication) {
|
||||
Text("Requires Authentication (Biometrics or Password)")
|
||||
}
|
||||
Spacer()
|
||||
}
|
||||
}
|
||||
.onExitCommand(perform: dismissalBlock)
|
||||
}
|
||||
HStack {
|
||||
Spacer()
|
||||
Button(action: dismissalBlock) {
|
||||
Text("Cancel")
|
||||
}
|
||||
Button(action: save) {
|
||||
Text("Create")
|
||||
}.disabled(name.isEmpty)
|
||||
}
|
||||
}.padding()
|
||||
}
|
||||
|
||||
func save() {
|
||||
try! store.create(name: name, requiresAuthentication: requiresAuthentication)
|
||||
dismissalBlock()
|
||||
}
|
||||
}
|
||||
@@ -1,60 +0,0 @@
|
||||
import SwiftUI
|
||||
import SecretKit
|
||||
|
||||
struct DeleteSecretView<StoreType: SecretStoreModifiable>: View {
|
||||
|
||||
let secret: StoreType.SecretType
|
||||
@ObservedObject var store: StoreType
|
||||
|
||||
@State var confirm = ""
|
||||
|
||||
fileprivate var dismissalBlock: (Bool) -> ()
|
||||
|
||||
init(secret: StoreType.SecretType, store: StoreType, dismissalBlock: @escaping (Bool) -> ()) {
|
||||
self.secret = secret
|
||||
self.store = store
|
||||
self.dismissalBlock = dismissalBlock
|
||||
}
|
||||
|
||||
var body: some View {
|
||||
VStack {
|
||||
HStack {
|
||||
Image(nsImage: NSApp.applicationIconImage)
|
||||
.resizable()
|
||||
.frame(width: 64, height: 64)
|
||||
.padding()
|
||||
VStack {
|
||||
HStack {
|
||||
Text("Delete \(secret.name)?").bold()
|
||||
Spacer()
|
||||
}
|
||||
HStack {
|
||||
Text("If you delete \(secret.name), you will not be able to recover it. Type \"\(secret.name)\" to confirm.")
|
||||
Spacer()
|
||||
}
|
||||
HStack {
|
||||
Text("Confirm Name:")
|
||||
TextField(secret.name, text: $confirm)
|
||||
}
|
||||
}
|
||||
.onExitCommand {
|
||||
self.dismissalBlock(false)
|
||||
}
|
||||
}
|
||||
HStack {
|
||||
Spacer()
|
||||
Button(action: delete) {
|
||||
Text("Delete")
|
||||
}.disabled(confirm != secret.name)
|
||||
Button(action: { self.dismissalBlock(false) }) {
|
||||
Text("Don't Delete")
|
||||
}
|
||||
}
|
||||
}.padding()
|
||||
}
|
||||
|
||||
func delete() {
|
||||
try! store.delete(secret: secret)
|
||||
self.dismissalBlock(true)
|
||||
}
|
||||
}
|
||||
@@ -1,57 +0,0 @@
|
||||
import SwiftUI
|
||||
|
||||
struct EmptyStoreView: View {
|
||||
|
||||
var body: some View {
|
||||
VStack {
|
||||
Text("No Secrets").bold()
|
||||
Text("Use your Smart Card's management tool to create a secret.")
|
||||
Text("Secretive only supports Elliptic Curve keys.")
|
||||
}.frame(maxWidth: .infinity, maxHeight: .infinity)
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
struct EmptyStoreModifiableView: View {
|
||||
|
||||
var body: some View {
|
||||
GeometryReader { windowGeometry in
|
||||
VStack {
|
||||
GeometryReader { g in
|
||||
Path { path in
|
||||
path.move(to: CGPoint(x: g.size.width / 2, y: g.size.height))
|
||||
path.addCurve(to:
|
||||
CGPoint(x: g.size.width * (3/4), y: g.size.height * (1/2)), control1:
|
||||
CGPoint(x: g.size.width / 2, y: g.size.height * (1/2)), control2:
|
||||
CGPoint(x: g.size.width * (3/4), y: g.size.height * (1/2)))
|
||||
path.addCurve(to:
|
||||
CGPoint(x: g.size.width, y: 0), control1:
|
||||
CGPoint(x: g.size.width, y: g.size.height * (1/2)), control2:
|
||||
CGPoint(x: g.size.width, y: 0))
|
||||
}.stroke(style: StrokeStyle(lineWidth: 5, lineCap: .round))
|
||||
Path { path in
|
||||
path.move(to: CGPoint(x: g.size.width - 10, y: 0))
|
||||
path.addLine(to: CGPoint(x: g.size.width, y: -10))
|
||||
path.addLine(to: CGPoint(x: g.size.width + 10, y: 0))
|
||||
}.fill()
|
||||
}.frame(height: (windowGeometry.size.height/2) - 20).padding()
|
||||
Text("No Secrets").bold()
|
||||
Text("Create a new one by clicking here.")
|
||||
Spacer()
|
||||
}.frame(maxWidth: .infinity, maxHeight: .infinity)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#if DEBUG
|
||||
|
||||
struct EmptyStoreModifiableView_Previews: PreviewProvider {
|
||||
static var previews: some View {
|
||||
Group {
|
||||
EmptyStoreView()
|
||||
EmptyStoreModifiableView()
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#endif
|
||||
@@ -1,57 +0,0 @@
|
||||
import Foundation
|
||||
import SwiftUI
|
||||
|
||||
struct NoticeView: View {
|
||||
|
||||
let text: String
|
||||
let severity: Severity
|
||||
let actionTitle: String?
|
||||
let action: (() -> Void)?
|
||||
|
||||
var body: some View {
|
||||
HStack {
|
||||
Text(text).bold()
|
||||
Spacer()
|
||||
if action != nil {
|
||||
Button(action: action!) {
|
||||
Text(actionTitle!)
|
||||
}
|
||||
}
|
||||
}.padding().background(color)
|
||||
}
|
||||
|
||||
var color: Color {
|
||||
switch severity {
|
||||
case .advisory:
|
||||
return Color.orange
|
||||
case .critical:
|
||||
return Color.red
|
||||
}
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
extension NoticeView {
|
||||
|
||||
enum Severity {
|
||||
case advisory, critical
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
#if DEBUG
|
||||
|
||||
struct NoticeView_Previews: PreviewProvider {
|
||||
static var previews: some View {
|
||||
Group {
|
||||
NoticeView(text: "Agent Not Running", severity: .advisory, actionTitle: "Run Setup") {
|
||||
print("OK")
|
||||
}
|
||||
NoticeView(text: "Critical Security Update Required", severity: .critical, actionTitle: "Update") {
|
||||
print("OK")
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#endif
|
||||
@@ -1,67 +0,0 @@
|
||||
import SwiftUI
|
||||
import SecretKit
|
||||
|
||||
struct SecretDetailView<SecretType: Secret>: View {
|
||||
|
||||
@State var secret: SecretType
|
||||
let keyWriter = OpenSSHKeyWriter()
|
||||
|
||||
var body: some View {
|
||||
Form {
|
||||
Section {
|
||||
GroupBox(label: Text("Fingerprint")) {
|
||||
HStack {
|
||||
Text(keyWriter.openSSHFingerprint(secret: secret))
|
||||
Spacer()
|
||||
}
|
||||
.frame(minWidth: 150, maxWidth: .infinity)
|
||||
.padding()
|
||||
}.onDrag {
|
||||
return NSItemProvider(item: NSData(data: self.keyWriter.openSSHFingerprint(secret: self.secret).data(using: .utf8)!), typeIdentifier: kUTTypeUTF8PlainText as String)
|
||||
}
|
||||
Spacer().frame(height: 10)
|
||||
GroupBox(label: Text("Public Key")) {
|
||||
VStack {
|
||||
Text(keyWriter.openSSHString(secret: secret))
|
||||
.multilineTextAlignment(.leading)
|
||||
.frame(minWidth: 150, maxWidth: .infinity)
|
||||
HStack {
|
||||
Spacer()
|
||||
Button(action: copy) {
|
||||
Text("Copy")
|
||||
}
|
||||
}
|
||||
}
|
||||
.padding()
|
||||
}
|
||||
.onDrag {
|
||||
return NSItemProvider(item: NSData(data: self.keyString.data(using: .utf8)!), typeIdentifier: kUTTypeUTF8PlainText as String)
|
||||
}
|
||||
Spacer()
|
||||
}
|
||||
}.padding()
|
||||
.frame(minHeight: 150, 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,133 +0,0 @@
|
||||
import Foundation
|
||||
import SwiftUI
|
||||
import ServiceManagement
|
||||
|
||||
struct SetupView: View {
|
||||
|
||||
var completion: ((Bool) -> Void)?
|
||||
|
||||
var body: some View {
|
||||
Form {
|
||||
SetupStepView<Spacer>(text: "Secretive needs to install a helper app to sign requests when the main app isn't running. This app is called \"SecretAgent\" and you might see it in Activity Manager from time to time.",
|
||||
index: 1,
|
||||
nestedView: nil,
|
||||
actionText: "Install") {
|
||||
self.installLaunchAgent()
|
||||
}
|
||||
SetupStepView(text: "You need to add a line to your shell config (.bashrc or .zshrc) telling SSH to talk to SecretAgent when it wants to authenticate. Drag this into your config file.",
|
||||
index: 2,
|
||||
nestedView: SetupStepCommandView(text: Constants.socketPrompt),
|
||||
actionText: "Added") {
|
||||
self.markAsDone()
|
||||
}
|
||||
HStack {
|
||||
Spacer()
|
||||
Button(action: { self.completion?(true) }) {
|
||||
Text("Finish")
|
||||
}
|
||||
.padding()
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
struct SetupStepView<NestedViewType: View>: View {
|
||||
|
||||
let text: String
|
||||
let index: Int
|
||||
let nestedView: NestedViewType?
|
||||
@State var completed = false
|
||||
let actionText: String
|
||||
let action: (() -> Bool)
|
||||
|
||||
var body: some View {
|
||||
Section {
|
||||
HStack {
|
||||
ZStack {
|
||||
if completed {
|
||||
Circle().foregroundColor(.green)
|
||||
.frame(width: 30, height: 30)
|
||||
Text("✓")
|
||||
.foregroundColor(.white)
|
||||
.bold()
|
||||
} else {
|
||||
Circle().foregroundColor(.blue)
|
||||
.frame(width: 30, height: 30)
|
||||
Text(String(describing: index))
|
||||
.foregroundColor(.white)
|
||||
.bold()
|
||||
}
|
||||
}
|
||||
.padding()
|
||||
VStack {
|
||||
Text(text)
|
||||
.opacity(completed ? 0.5 : 1)
|
||||
.lineLimit(nil)
|
||||
.frame(idealHeight: 0, maxHeight: .infinity)
|
||||
if nestedView != nil {
|
||||
Spacer()
|
||||
nestedView!
|
||||
}
|
||||
}
|
||||
.padding()
|
||||
Button(action: {
|
||||
self.completed = self.action()
|
||||
}) {
|
||||
Text(actionText)
|
||||
}.disabled(completed)
|
||||
.padding()
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
struct SetupStepCommandView: View {
|
||||
|
||||
let text: String
|
||||
|
||||
var body: some View {
|
||||
Text(text)
|
||||
.font(.system(.caption, design: .monospaced))
|
||||
.lineLimit(nil)
|
||||
.frame(idealHeight: 0, maxHeight: .infinity)
|
||||
.padding()
|
||||
.background(Color(white: 0, opacity: 0.10))
|
||||
.cornerRadius(10)
|
||||
.onDrag {
|
||||
return NSItemProvider(item: NSData(data: self.text.data(using: .utf8)!), typeIdentifier: kUTTypeUTF8PlainText as String)
|
||||
}
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
extension SetupView {
|
||||
|
||||
func installLaunchAgent() -> Bool {
|
||||
SMLoginItemSetEnabled("com.maxgoedjen.Secretive.SecretAgent" as CFString, true)
|
||||
}
|
||||
|
||||
func markAsDone() -> Bool {
|
||||
return true
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
extension SetupView {
|
||||
|
||||
enum Constants {
|
||||
static let socketPath = (NSHomeDirectory().replacingOccurrences(of: "com.maxgoedjen.Secretive.Host", with: "com.maxgoedjen.Secretive.SecretAgent") as NSString).appendingPathComponent("socket.ssh") as String
|
||||
static let socketPrompt = "export SSH_AUTH_SOCK=\(socketPath)"
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
#if DEBUG
|
||||
|
||||
struct SetupView_Previews: PreviewProvider {
|
||||
static var previews: some View {
|
||||
SetupView()
|
||||
}
|
||||
}
|
||||
|
||||
#endif
|
||||
@@ -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,28 +0,0 @@
|
||||
//
|
||||
// SecretiveTests.swift
|
||||
// SecretiveTests
|
||||
//
|
||||
// Created by Max Goedjen on 2/18/20.
|
||||
// Copyright © 2020 Max Goedjen. All rights reserved.
|
||||
//
|
||||
|
||||
import XCTest
|
||||
@testable import Secretive
|
||||
|
||||
class SecretiveTests: XCTestCase {
|
||||
|
||||
override func setUp() {
|
||||
// Put setup code here. This method is called before the invocation of each test method in the class.
|
||||
}
|
||||
|
||||
override func tearDown() {
|
||||
// Put teardown code here. This method is called after the invocation of each test method in the class.
|
||||
}
|
||||
|
||||
func testExample() {
|
||||
// This is an example of a functional test case.
|
||||
// Use XCTAssert and related functions to verify your tests produce the correct results.
|
||||
}
|
||||
|
||||
|
||||
}
|
||||
3
Sources/Config/Config.xcconfig
Normal file
@@ -0,0 +1,3 @@
|
||||
CI_VERSION = GITHUB_CI_VERSION
|
||||
CI_BUILD_NUMBER = GITHUB_BUILD_NUMBER
|
||||
CI_BUILD_LINK = GITHUB_BUILD_URL
|
||||
38
Sources/Config/Secretive.xctestplan
Normal file
@@ -0,0 +1,38 @@
|
||||
{
|
||||
"configurations" : [
|
||||
{
|
||||
"id" : "5896AE5A-6D5A-48D3-837B-668B646A3273",
|
||||
"name" : "Configuration 1",
|
||||
"options" : {
|
||||
|
||||
}
|
||||
}
|
||||
],
|
||||
"defaultOptions" : {
|
||||
|
||||
},
|
||||
"testTargets" : [
|
||||
{
|
||||
"target" : {
|
||||
"containerPath" : "container:Packages",
|
||||
"identifier" : "BriefTests",
|
||||
"name" : "BriefTests"
|
||||
}
|
||||
},
|
||||
{
|
||||
"target" : {
|
||||
"containerPath" : "container:Packages",
|
||||
"identifier" : "SecretKitTests",
|
||||
"name" : "SecretKitTests"
|
||||
}
|
||||
},
|
||||
{
|
||||
"target" : {
|
||||
"containerPath" : "container:Packages",
|
||||
"identifier" : "SecretAgentKitTests",
|
||||
"name" : "SecretAgentKitTests"
|
||||
}
|
||||
}
|
||||
],
|
||||
"version" : 1
|
||||
}
|
||||
95
Sources/Packages/Package.swift
Normal file
@@ -0,0 +1,95 @@
|
||||
// swift-tools-version:6.2
|
||||
// The swift-tools-version declares the minimum version of Swift required to build this package.
|
||||
|
||||
import PackageDescription
|
||||
|
||||
let package = Package(
|
||||
name: "SecretivePackages",
|
||||
defaultLocalization: "en",
|
||||
platforms: [
|
||||
.macOS(.v14)
|
||||
],
|
||||
products: [
|
||||
.library(
|
||||
name: "SecretKit",
|
||||
targets: ["SecretKit"]),
|
||||
.library(
|
||||
name: "SecureEnclaveSecretKit",
|
||||
targets: ["SecureEnclaveSecretKit"]),
|
||||
.library(
|
||||
name: "SmartCardSecretKit",
|
||||
targets: ["SmartCardSecretKit"]),
|
||||
.library(
|
||||
name: "SecretAgentKit",
|
||||
targets: ["SecretAgentKit", "XPCWrappers"]),
|
||||
.library(
|
||||
name: "Brief",
|
||||
targets: ["Brief"]),
|
||||
.library(
|
||||
name: "XPCWrappers",
|
||||
targets: ["XPCWrappers"]),
|
||||
],
|
||||
dependencies: [
|
||||
],
|
||||
targets: [
|
||||
.target(
|
||||
name: "SecretKit",
|
||||
dependencies: [],
|
||||
resources: [localization],
|
||||
swiftSettings: swiftSettings,
|
||||
),
|
||||
.testTarget(
|
||||
name: "SecretKitTests",
|
||||
dependencies: ["SecretKit", "SecureEnclaveSecretKit", "SmartCardSecretKit"],
|
||||
swiftSettings: swiftSettings,
|
||||
),
|
||||
.target(
|
||||
name: "SecureEnclaveSecretKit",
|
||||
dependencies: ["SecretKit"],
|
||||
resources: [localization],
|
||||
swiftSettings: swiftSettings,
|
||||
),
|
||||
.target(
|
||||
name: "SmartCardSecretKit",
|
||||
dependencies: ["SecretKit"],
|
||||
resources: [localization],
|
||||
swiftSettings: swiftSettings,
|
||||
),
|
||||
.target(
|
||||
name: "SecretAgentKit",
|
||||
dependencies: ["SecretKit"],
|
||||
resources: [localization],
|
||||
swiftSettings: swiftSettings,
|
||||
),
|
||||
.testTarget(
|
||||
name: "SecretAgentKitTests",
|
||||
dependencies: ["SecretAgentKit"],
|
||||
),
|
||||
.target(
|
||||
name: "Brief",
|
||||
dependencies: ["XPCWrappers"],
|
||||
resources: [localization],
|
||||
swiftSettings: swiftSettings,
|
||||
),
|
||||
.testTarget(
|
||||
name: "BriefTests",
|
||||
dependencies: ["Brief"],
|
||||
),
|
||||
.target(
|
||||
name: "XPCWrappers",
|
||||
swiftSettings: swiftSettings,
|
||||
),
|
||||
]
|
||||
)
|
||||
|
||||
var localization: Resource {
|
||||
.process("../../Resources/Localizable.xcstrings")
|
||||
}
|
||||
|
||||
var swiftSettings: [PackageDescription.SwiftSetting] {
|
||||
[
|
||||
.swiftLanguageMode(.v6),
|
||||
.treatAllWarnings(as: .error),
|
||||
.strictMemorySafety()
|
||||
]
|
||||
}
|
||||
26673
Sources/Packages/Resources/Localizable.xcstrings
Normal file
@@ -0,0 +1,15 @@
|
||||
# ``Brief``
|
||||
|
||||
Brief is a collection of protocols and concrete implmentation describing updates.
|
||||
|
||||
## Topics
|
||||
|
||||
### Versioning
|
||||
|
||||
- ``SemVer``
|
||||
- ``Release``
|
||||
|
||||
### Updater
|
||||
|
||||
- ``UpdaterProtocol``
|
||||
- ``Updater``
|
||||
133
Sources/Packages/Sources/Brief/Release.swift
Normal file
@@ -0,0 +1,133 @@
|
||||
import Foundation
|
||||
import SwiftUI
|
||||
|
||||
/// A release is a representation of a downloadable update.
|
||||
public struct Release: Codable, Sendable, Hashable {
|
||||
|
||||
/// 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
|
||||
|
||||
public let attributedBody: AttributedString
|
||||
|
||||
/// 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
|
||||
self.attributedBody = AttributedString(_markdown: body)
|
||||
}
|
||||
|
||||
public init(_ release: GitHubRelease) {
|
||||
self.name = release.name
|
||||
self.prerelease = release.prerelease
|
||||
self.html_url = release.html_url
|
||||
self.body = release.body
|
||||
self.attributedBody = AttributedString(_markdown: release.body)
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
public struct GitHubRelease: Codable, Sendable {
|
||||
let name: String
|
||||
let prerelease: Bool
|
||||
let html_url: URL
|
||||
let body: String
|
||||
}
|
||||
|
||||
fileprivate extension AttributedString {
|
||||
|
||||
init(_markdown markdown: String) {
|
||||
let split = markdown.split(whereSeparator: \.isNewline)
|
||||
let lines = split
|
||||
.compactMap {
|
||||
try? AttributedString(markdown: String($0), options: .init(allowsExtendedAttributes: true, interpretedSyntax: .full))
|
||||
}
|
||||
.map { (string: AttributedString) in
|
||||
guard case let .header(level) = string.runs.first?.presentationIntent?.components.first?.kind else { return string }
|
||||
return AttributedString("\n") + string
|
||||
.transformingAttributes(\.font) { font in
|
||||
font.value = switch level {
|
||||
case 2: .headline.bold()
|
||||
case 3: .headline
|
||||
default: .subheadline
|
||||
}
|
||||
}
|
||||
.transformingAttributes(\.underlineStyle) { underline in
|
||||
underline.value = switch level {
|
||||
case 2: .single
|
||||
default: .none
|
||||
}
|
||||
}
|
||||
+ AttributedString("\n")
|
||||
}
|
||||
self = lines.reduce(into: AttributedString()) { partialResult, next in
|
||||
partialResult.append(next)
|
||||
partialResult.append(AttributedString("\n"))
|
||||
}
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
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"
|
||||
}
|
||||
|
||||
}
|
||||
52
Sources/Packages/Sources/Brief/SemVer.swift
Normal file
@@ -0,0 +1,52 @@
|
||||
import Foundation
|
||||
|
||||
/// A representation of a Semantic Version.
|
||||
public struct SemVer: Sendable {
|
||||
|
||||
/// The SemVer broken into an array of integers.
|
||||
let versionNumbers: [Int]
|
||||
public let previewDescription: String?
|
||||
|
||||
public var isTestBuild: Bool {
|
||||
versionNumbers == [0, 0, 0]
|
||||
}
|
||||
|
||||
/// 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
|
||||
// Nightlies have the format 0.0.0_nightly-2025-09-03
|
||||
let splitFull = version.split(separator: "_")
|
||||
let strippedBeta = splitFull.first!
|
||||
previewDescription = splitFull.count > 1 ? String(splitFull[1]) : nil
|
||||
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]
|
||||
previewDescription = nil
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
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
|
||||
}
|
||||
|
||||
|
||||
}
|
||||
101
Sources/Packages/Sources/Brief/Updater.swift
Normal file
@@ -0,0 +1,101 @@
|
||||
import Foundation
|
||||
import Observation
|
||||
import XPCWrappers
|
||||
|
||||
/// A concrete implementation of ``UpdaterProtocol`` which considers the current release and OS version.
|
||||
@Observable public final class Updater: UpdaterProtocol, Sendable {
|
||||
|
||||
private let state = State()
|
||||
@MainActor @Observable public final class State {
|
||||
var update: Release? = nil
|
||||
nonisolated init() {}
|
||||
}
|
||||
public var update: Release? {
|
||||
state.update
|
||||
}
|
||||
|
||||
/// The current version of the app that is running.
|
||||
public let currentVersion: SemVer
|
||||
|
||||
/// The current OS version.
|
||||
private let osVersion: 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
|
||||
Task {
|
||||
if checkOnLaunch {
|
||||
try await checkForUpdates()
|
||||
}
|
||||
while !Task.isCancelled {
|
||||
try? await Task.sleep(for: .seconds(Int(checkFrequency)))
|
||||
try await checkForUpdates()
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// Manually trigger an update check.
|
||||
public func checkForUpdates() async throws {
|
||||
let session = try await XPCTypedSession<[Release], Never>(serviceName: "com.maxgoedjen.Secretive.SecretiveUpdater")
|
||||
await evaluate(releases: try await session.send())
|
||||
session.complete()
|
||||
}
|
||||
|
||||
|
||||
/// Ignores a specified release. `update` will be nil if the user has ignored the latest available release.
|
||||
/// - Parameter release: The release to ignore.
|
||||
public func ignore(release: Release) async {
|
||||
guard !release.critical else { return }
|
||||
defaults.set(true, forKey: release.name)
|
||||
await MainActor.run {
|
||||
state.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]) async {
|
||||
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 {
|
||||
await MainActor.run {
|
||||
state.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")!
|
||||
}
|
||||
|
||||
}
|
||||
13
Sources/Packages/Sources/Brief/UpdaterProtocol.swift
Normal file
@@ -0,0 +1,13 @@
|
||||
import Foundation
|
||||
|
||||
/// A protocol for retreiving the latest available version of an app.
|
||||
public protocol UpdaterProtocol: Observable, Sendable {
|
||||
|
||||
/// The latest update
|
||||
@MainActor var update: Release? { get }
|
||||
|
||||
var currentVersion: SemVer { get }
|
||||
|
||||
func ignore(release: Release) async
|
||||
}
|
||||
|
||||
157
Sources/Packages/Sources/SecretAgentKit/Agent.swift
Normal file
@@ -0,0 +1,157 @@
|
||||
import Foundation
|
||||
import CryptoKit
|
||||
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 final class Agent: Sendable {
|
||||
|
||||
private let storeList: SecretStoreList
|
||||
private let witness: SigningWitness?
|
||||
private let publicKeyWriter = OpenSSHPublicKeyWriter()
|
||||
private let signatureWriter = OpenSSHSignatureWriter()
|
||||
private let certificateHandler = OpenSSHCertificateHandler()
|
||||
private let logger = Logger(subsystem: "com.maxgoedjen.secretive.secretagent", category: "Agent")
|
||||
|
||||
/// Initializes an agent with a store list and a witness.
|
||||
/// - Parameters:
|
||||
/// - storeList: The `SecretStoreList` to make available.
|
||||
/// - witness: A witness to notify of requests.
|
||||
public init(storeList: SecretStoreList, witness: SigningWitness? = nil) {
|
||||
logger.debug("Agent is running")
|
||||
self.storeList = storeList
|
||||
self.witness = witness
|
||||
Task { @MainActor in
|
||||
await certificateHandler.reloadCertificates(for: storeList.allSecrets)
|
||||
}
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
extension Agent {
|
||||
|
||||
public func handle(request: SSHAgent.Request, provenance: SigningRequestProvenance) async -> Data {
|
||||
// Depending on the launch context (such as after macOS update), the agent may need to reload secrets before acting
|
||||
await reloadSecretsIfNeccessary()
|
||||
var response = Data()
|
||||
do {
|
||||
switch request {
|
||||
case .requestIdentities:
|
||||
response.append(SSHAgent.Response.agentIdentitiesAnswer.data)
|
||||
response.append(await identities())
|
||||
logger.debug("Agent returned \(SSHAgent.Response.agentIdentitiesAnswer.debugDescription)")
|
||||
case .signRequest(let context):
|
||||
response.append(SSHAgent.Response.agentSignResponse.data)
|
||||
response.append(try await sign(data: context.dataToSign, keyBlob: context.keyBlob, provenance: provenance))
|
||||
logger.debug("Agent returned \(SSHAgent.Response.agentSignResponse.debugDescription)")
|
||||
case .unknown(let value):
|
||||
logger.error("Agent received unknown request of type \(value).")
|
||||
throw UnhandledRequestError()
|
||||
default:
|
||||
logger.debug("Agent received valid request of type \(request.debugDescription), but not currently supported.")
|
||||
throw UnhandledRequestError()
|
||||
}
|
||||
} catch {
|
||||
response = SSHAgent.Response.agentFailure.data
|
||||
logger.debug("Agent returned \(SSHAgent.Response.agentFailure.debugDescription)")
|
||||
}
|
||||
return response.lengthAndData
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
extension Agent {
|
||||
|
||||
/// Lists the identities available for signing operations
|
||||
/// - Returns: An OpenSSH formatted Data payload listing the identities available for signing operations.
|
||||
func identities() async -> Data {
|
||||
let secrets = await storeList.allSecrets
|
||||
await certificateHandler.reloadCertificates(for: secrets)
|
||||
var count = 0
|
||||
var keyData = Data()
|
||||
|
||||
for secret in secrets {
|
||||
let keyBlob = publicKeyWriter.data(secret: secret)
|
||||
keyData.append(keyBlob.lengthAndData)
|
||||
keyData.append(publicKeyWriter.comment(secret: secret).lengthAndData)
|
||||
count += 1
|
||||
|
||||
if let (certificateData, name) = try? await certificateHandler.keyBlobAndName(for: secret) {
|
||||
keyData.append(certificateData.lengthAndData)
|
||||
keyData.append(name.lengthAndData)
|
||||
count += 1
|
||||
}
|
||||
}
|
||||
logger.log("Agent enumerated \(count) identities")
|
||||
var countBigEndian = UInt32(count).bigEndian
|
||||
let countData = unsafe Data(bytes: &countBigEndian, count: MemoryLayout<UInt32>.size)
|
||||
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, keyBlob: Data, provenance: SigningRequestProvenance) async throws -> Data {
|
||||
guard let (secret, store) = await secret(matching: keyBlob) else {
|
||||
let keyBlobHex = keyBlob.compactMap { ("0" + String($0, radix: 16, uppercase: false)).suffix(2) }.joined()
|
||||
logger.debug("Agent did not have a key matching \(keyBlobHex)")
|
||||
throw NoMatchingKeyError()
|
||||
}
|
||||
|
||||
try await witness?.speakNowOrForeverHoldYourPeace(forAccessTo: secret, from: store, by: provenance)
|
||||
|
||||
let rawRepresentation = try await store.sign(data: data, with: secret, for: provenance)
|
||||
let signedData = signatureWriter.data(secret: secret, signature: rawRepresentation)
|
||||
|
||||
try await witness?.witness(accessTo: secret, from: store, by: provenance)
|
||||
|
||||
logger.debug("Agent signed request")
|
||||
|
||||
return signedData
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
extension Agent {
|
||||
|
||||
/// Gives any store with no loaded secrets a chance to reload.
|
||||
func reloadSecretsIfNeccessary() async {
|
||||
for store in await storeList.stores {
|
||||
if await store.secrets.isEmpty {
|
||||
let name = await store.name
|
||||
logger.debug("Store \(name, privacy: .public) has no loaded secrets. Reloading.")
|
||||
await store.reloadSecrets()
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// Finds a ``Secret`` matching a specified hash whos signature was requested.
|
||||
/// - Parameter hash: The hash to match against.
|
||||
/// - Returns: A ``Secret`` and the ``SecretStore`` containing it, if a match is found.
|
||||
func secret(matching hash: Data) async -> (AnySecret, AnySecretStore)? {
|
||||
await storeList.allSecretsWithStores.first {
|
||||
hash == publicKeyWriter.data(secret: $0.0)
|
||||
}
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
|
||||
extension Agent {
|
||||
|
||||
struct NoMatchingKeyError: Error {}
|
||||
struct UnhandledRequestError: Error {}
|
||||
|
||||
}
|
||||
|
||||
extension SSHAgent.Response {
|
||||
|
||||
var data: Data {
|
||||
var raw = self.rawValue
|
||||
return unsafe Data(bytes: &raw, count: MemoryLayout<UInt8>.size)
|
||||
}
|
||||
|
||||
}
|
||||
@@ -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``
|
||||
@@ -0,0 +1,12 @@
|
||||
import Foundation
|
||||
|
||||
extension FileHandle {
|
||||
|
||||
public var pidOfConnectedProcess: Int32 {
|
||||
let pidPointer = UnsafeMutableRawPointer.allocate(byteCount: MemoryLayout<Int32>.size, alignment: 1)
|
||||
var len = socklen_t(MemoryLayout<Int32>.size)
|
||||
unsafe getsockopt(fileDescriptor, SOCK_STREAM, LOCAL_PEERPID, pidPointer, &len)
|
||||
return unsafe pidPointer.load(as: Int32.self)
|
||||
}
|
||||
|
||||
}
|
||||
@@ -0,0 +1,88 @@
|
||||
import Foundation
|
||||
import OSLog
|
||||
import SecretKit
|
||||
|
||||
/// Manages storage and lookup for OpenSSH certificates.
|
||||
public actor OpenSSHCertificateHandler: Sendable {
|
||||
|
||||
private let publicKeyFileStoreController = PublicKeyFileStoreController(homeDirectory: URL.homeDirectory)
|
||||
private let logger = Logger(subsystem: "com.maxgoedjen.secretive.secretagent", category: "OpenSSHCertificateHandler")
|
||||
private let writer = OpenSSHPublicKeyWriter()
|
||||
private var keyBlobsAndNames: [AnySecret: (Data, Data)] = [:]
|
||||
|
||||
/// Initializes an OpenSSHCertificateHandler.
|
||||
public init() {
|
||||
}
|
||||
|
||||
/// Reloads any certificates in the PublicKeys folder.
|
||||
/// - Parameter secrets: the secrets to look up corresponding certificates for.
|
||||
public func reloadCertificates(for secrets: [AnySecret]) {
|
||||
guard publicKeyFileStoreController.hasAnyCertificates else {
|
||||
logger.log("No certificates, short circuiting")
|
||||
return
|
||||
}
|
||||
keyBlobsAndNames = secrets.reduce(into: [:]) { partialResult, next in
|
||||
partialResult[next] = try? loadKeyblobAndName(for: next)
|
||||
}
|
||||
}
|
||||
|
||||
/// Attempts to find an OpenSSH Certificate that corresponds to a ``Secret``
|
||||
/// - Parameter secret: The secret to search for a certificate with
|
||||
/// - Returns: A (``Data``, ``Data``) tuple containing the certificate and certificate name, respectively.
|
||||
public func keyBlobAndName<SecretType: Secret>(for secret: SecretType) throws -> (Data, Data)? {
|
||||
keyBlobsAndNames[AnySecret(secret)]
|
||||
}
|
||||
|
||||
/// Attempts to find an OpenSSH Certificate that corresponds to a ``Secret``
|
||||
/// - Parameter secret: The secret to search for a certificate with
|
||||
/// - Returns: A (``Data``, ``Data``) tuple containing the certificate and certificate name, respectively.
|
||||
private func loadKeyblobAndName<SecretType: Secret>(for secret: SecretType) throws -> (Data, Data)? {
|
||||
let certificatePath = publicKeyFileStoreController.sshCertificatePath(for: secret)
|
||||
guard FileManager.default.fileExists(atPath: certificatePath) else {
|
||||
return nil
|
||||
}
|
||||
|
||||
logger.debug("Found certificate for \(secret.name)")
|
||||
let certContent = try String(contentsOfFile:certificatePath, encoding: .utf8)
|
||||
let certElements = certContent.trimmingCharacters(in: .whitespacesAndNewlines).components(separatedBy: " ")
|
||||
|
||||
guard certElements.count >= 2 else {
|
||||
logger.warning("Certificate found for \(secret.name) but failed to load")
|
||||
throw OpenSSHCertificateError.parsingFailed
|
||||
}
|
||||
guard let certDecoded = Data(base64Encoded: certElements[1] as String) else {
|
||||
logger.warning("Certificate found for \(secret.name) but failed to decode base64 key")
|
||||
throw OpenSSHCertificateError.parsingFailed
|
||||
}
|
||||
|
||||
if certElements.count >= 3 {
|
||||
let certName = Data(certElements[2].utf8)
|
||||
return (certDecoded, certName)
|
||||
}
|
||||
let certName = Data(secret.name.utf8)
|
||||
logger.info("Certificate for \(secret.name) does not have a name tag, using secret name instead")
|
||||
return (certDecoded, certName)
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
extension OpenSSHCertificateHandler {
|
||||
|
||||
enum OpenSSHCertificateError: LocalizedError {
|
||||
case unsupportedType
|
||||
case parsingFailed
|
||||
case doesNotExist
|
||||
|
||||
public var errorDescription: String? {
|
||||
switch self {
|
||||
case .unsupportedType:
|
||||
return "The key type was unsupported"
|
||||
case .parsingFailed:
|
||||
return "Failed to properly parse the SSH certificate"
|
||||
case .doesNotExist:
|
||||
return "Certificate does not exist"
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
}
|
||||
47
Sources/Packages/Sources/SecretAgentKit/OpenSSHReader.swift
Normal file
@@ -0,0 +1,47 @@
|
||||
import Foundation
|
||||
|
||||
/// Reads OpenSSH protocol data.
|
||||
final class OpenSSHReader {
|
||||
|
||||
var remaining: Data
|
||||
|
||||
/// Initialize the reader with an OpenSSH data payload.
|
||||
/// - Parameter data: The data to read.
|
||||
init(data: Data) {
|
||||
remaining = Data(data)
|
||||
}
|
||||
|
||||
/// Reads the next chunk of data from the playload.
|
||||
/// - Returns: The next chunk of data.
|
||||
func readNextChunk(convertEndianness: Bool = true) throws(OpenSSHReaderError) -> Data {
|
||||
let littleEndianLength = try readNextBytes(as: UInt32.self)
|
||||
let length = convertEndianness ? Int(littleEndianLength.bigEndian) : Int(littleEndianLength)
|
||||
guard remaining.count >= length else { throw .beyondBounds }
|
||||
let dataRange = 0..<length
|
||||
let ret = Data(remaining[dataRange])
|
||||
remaining.removeSubrange(dataRange)
|
||||
return ret
|
||||
}
|
||||
|
||||
func readNextBytes<T>(as: T.Type) throws(OpenSSHReaderError) -> T {
|
||||
let size = MemoryLayout<T>.size
|
||||
guard remaining.count >= size else { throw .beyondBounds }
|
||||
let lengthRange = 0..<size
|
||||
let lengthChunk = remaining[lengthRange]
|
||||
remaining.removeSubrange(lengthRange)
|
||||
return unsafe lengthChunk.bytes.unsafeLoad(as: T.self)
|
||||
}
|
||||
|
||||
func readNextChunkAsString(convertEndianness: Bool = true) throws(OpenSSHReaderError) -> String {
|
||||
try String(decoding: readNextChunk(convertEndianness: convertEndianness), as: UTF8.self)
|
||||
}
|
||||
|
||||
func readNextChunkAsSubReader(convertEndianness: Bool = true) throws(OpenSSHReaderError) -> OpenSSHReader {
|
||||
OpenSSHReader(data: try readNextChunk(convertEndianness: convertEndianness))
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
public enum OpenSSHReaderError: Error, Codable {
|
||||
case beyondBounds
|
||||
}
|
||||
@@ -0,0 +1,109 @@
|
||||
import Foundation
|
||||
import OSLog
|
||||
import SecretKit
|
||||
|
||||
public protocol SSHAgentInputParserProtocol {
|
||||
|
||||
func parse(data: Data) async throws -> SSHAgent.Request
|
||||
|
||||
}
|
||||
|
||||
public struct SSHAgentInputParser: SSHAgentInputParserProtocol {
|
||||
|
||||
private let logger = Logger(subsystem: "com.maxgoedjen.secretive.secretagent", category: "InputParser")
|
||||
|
||||
public init() {
|
||||
|
||||
}
|
||||
|
||||
public func parse(data: Data) throws(AgentParsingError) -> SSHAgent.Request {
|
||||
logger.debug("Parsing new data")
|
||||
guard data.count > 4 else {
|
||||
throw .invalidData
|
||||
}
|
||||
let specifiedLength = unsafe (data[0..<4].bytes.unsafeLoad(as: UInt32.self).bigEndian) + 4
|
||||
let rawRequestInt = data[4]
|
||||
let remainingDataRange = 5..<min(Int(specifiedLength), data.count)
|
||||
lazy var body: Data = { Data(data[remainingDataRange]) }()
|
||||
switch rawRequestInt {
|
||||
case SSHAgent.Request.requestIdentities.protocolID:
|
||||
return .requestIdentities
|
||||
case SSHAgent.Request.signRequest(.empty).protocolID:
|
||||
do {
|
||||
return .signRequest(try signatureRequestContext(from: body))
|
||||
} catch {
|
||||
throw .openSSHReader(error)
|
||||
}
|
||||
case SSHAgent.Request.addIdentity.protocolID:
|
||||
return .addIdentity
|
||||
case SSHAgent.Request.removeIdentity.protocolID:
|
||||
return .removeIdentity
|
||||
case SSHAgent.Request.removeAllIdentities.protocolID:
|
||||
return .removeAllIdentities
|
||||
case SSHAgent.Request.addIDConstrained.protocolID:
|
||||
return .addIDConstrained
|
||||
case SSHAgent.Request.addSmartcardKey.protocolID:
|
||||
return .addSmartcardKey
|
||||
case SSHAgent.Request.removeSmartcardKey.protocolID:
|
||||
return .removeSmartcardKey
|
||||
case SSHAgent.Request.lock.protocolID:
|
||||
return .lock
|
||||
case SSHAgent.Request.unlock.protocolID:
|
||||
return .unlock
|
||||
case SSHAgent.Request.addSmartcardKeyConstrained.protocolID:
|
||||
return .addSmartcardKeyConstrained
|
||||
case SSHAgent.Request.protocolExtension.protocolID:
|
||||
return .protocolExtension
|
||||
default:
|
||||
return .unknown(rawRequestInt)
|
||||
}
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
extension SSHAgentInputParser {
|
||||
|
||||
func signatureRequestContext(from data: Data) throws(OpenSSHReaderError) -> SSHAgent.Request.SignatureRequestContext {
|
||||
let reader = OpenSSHReader(data: data)
|
||||
let rawKeyBlob = try reader.readNextChunk()
|
||||
let keyBlob = certificatePublicKeyBlob(from: rawKeyBlob) ?? rawKeyBlob
|
||||
let dataToSign = try reader.readNextChunk()
|
||||
return SSHAgent.Request.SignatureRequestContext(keyBlob: keyBlob, dataToSign: dataToSign)
|
||||
}
|
||||
|
||||
func certificatePublicKeyBlob(from hash: Data) -> Data? {
|
||||
let reader = OpenSSHReader(data: hash)
|
||||
do {
|
||||
let certType = String(decoding: try reader.readNextChunk(), as: UTF8.self)
|
||||
switch certType {
|
||||
case "ecdsa-sha2-nistp256-cert-v01@openssh.com",
|
||||
"ecdsa-sha2-nistp384-cert-v01@openssh.com",
|
||||
"ecdsa-sha2-nistp521-cert-v01@openssh.com":
|
||||
_ = try reader.readNextChunk() // nonce
|
||||
let curveIdentifier = try reader.readNextChunk()
|
||||
let publicKey = try reader.readNextChunk()
|
||||
let openSSHIdentifier = certType.replacingOccurrences(of: "-cert-v01@openssh.com", with: "")
|
||||
return openSSHIdentifier.lengthAndData +
|
||||
curveIdentifier.lengthAndData +
|
||||
publicKey.lengthAndData
|
||||
default:
|
||||
return nil
|
||||
}
|
||||
} catch {
|
||||
return nil
|
||||
}
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
|
||||
extension SSHAgentInputParser {
|
||||
|
||||
public enum AgentParsingError: Error, Codable {
|
||||
case unknownRequest
|
||||
case unhandledRequest
|
||||
case invalidData
|
||||
case openSSHReader(OpenSSHReaderError)
|
||||
}
|
||||
|
||||
}
|
||||
@@ -0,0 +1,99 @@
|
||||
import Foundation
|
||||
|
||||
/// A namespace for the SSH Agent Protocol, as described in https://datatracker.ietf.org/doc/html/draft-miller-ssh-agent#section-5.1
|
||||
public enum SSHAgent {}
|
||||
|
||||
extension SSHAgent {
|
||||
|
||||
/// The type of the SSH Agent Request, as described in https://datatracker.ietf.org/doc/html/draft-miller-ssh-agent#section-5.1
|
||||
public enum Request: CustomDebugStringConvertible, Codable, Sendable {
|
||||
|
||||
case requestIdentities
|
||||
case signRequest(SignatureRequestContext)
|
||||
case addIdentity
|
||||
case removeIdentity
|
||||
case removeAllIdentities
|
||||
case addIDConstrained
|
||||
case addSmartcardKey
|
||||
case removeSmartcardKey
|
||||
case lock
|
||||
case unlock
|
||||
case addSmartcardKeyConstrained
|
||||
case protocolExtension
|
||||
case unknown(UInt8)
|
||||
|
||||
public var protocolID: UInt8 {
|
||||
switch self {
|
||||
case .requestIdentities: 11
|
||||
case .signRequest: 13
|
||||
case .addIdentity: 17
|
||||
case .removeIdentity: 18
|
||||
case .removeAllIdentities: 19
|
||||
case .addIDConstrained: 25
|
||||
case .addSmartcardKey: 20
|
||||
case .removeSmartcardKey: 21
|
||||
case .lock: 22
|
||||
case .unlock: 23
|
||||
case .addSmartcardKeyConstrained: 26
|
||||
case .protocolExtension: 27
|
||||
case .unknown(let value): value
|
||||
}
|
||||
}
|
||||
|
||||
public var debugDescription: String {
|
||||
switch self {
|
||||
case .requestIdentities: "SSH_AGENTC_REQUEST_IDENTITIES"
|
||||
case .signRequest: "SSH_AGENTC_SIGN_REQUEST"
|
||||
case .addIdentity: "SSH_AGENTC_ADD_IDENTITY"
|
||||
case .removeIdentity: "SSH_AGENTC_REMOVE_IDENTITY"
|
||||
case .removeAllIdentities: "SSH_AGENTC_REMOVE_ALL_IDENTITIES"
|
||||
case .addIDConstrained: "SSH_AGENTC_ADD_ID_CONSTRAINED"
|
||||
case .addSmartcardKey: "SSH_AGENTC_ADD_SMARTCARD_KEY"
|
||||
case .removeSmartcardKey: "SSH_AGENTC_REMOVE_SMARTCARD_KEY"
|
||||
case .lock: "SSH_AGENTC_LOCK"
|
||||
case .unlock: "SSH_AGENTC_UNLOCK"
|
||||
case .addSmartcardKeyConstrained: "SSH_AGENTC_ADD_SMARTCARD_KEY_CONSTRAINED"
|
||||
case .protocolExtension: "SSH_AGENTC_EXTENSION"
|
||||
case .unknown: "UNKNOWN_MESSAGE"
|
||||
}
|
||||
}
|
||||
|
||||
public struct SignatureRequestContext: Sendable, Codable {
|
||||
public let keyBlob: Data
|
||||
public let dataToSign: Data
|
||||
|
||||
public init(keyBlob: Data, dataToSign: Data) {
|
||||
self.keyBlob = keyBlob
|
||||
self.dataToSign = dataToSign
|
||||
}
|
||||
|
||||
public static var empty: SignatureRequestContext {
|
||||
SignatureRequestContext(keyBlob: Data(), dataToSign: Data())
|
||||
}
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
/// The type of the SSH Agent Response, as described in https://datatracker.ietf.org/doc/html/draft-miller-ssh-agent#section-5.1
|
||||
public enum Response: UInt8, CustomDebugStringConvertible {
|
||||
|
||||
case agentFailure = 5
|
||||
case agentSuccess = 6
|
||||
case agentIdentitiesAnswer = 12
|
||||
case agentSignResponse = 14
|
||||
case agentExtensionFailure = 28
|
||||
case agentExtensionResponse = 29
|
||||
|
||||
public var debugDescription: String {
|
||||
switch self {
|
||||
case .agentFailure: "SSH_AGENT_FAILURE"
|
||||
case .agentSuccess: "SSH_AGENT_SUCCESS"
|
||||
case .agentIdentitiesAnswer: "SSH_AGENT_IDENTITIES_ANSWER"
|
||||
case .agentSignResponse: "SSH_AGENT_SIGN_RESPONSE"
|
||||
case .agentExtensionFailure: "SSH_AGENT_EXTENSION_FAILURE"
|
||||
case .agentExtensionResponse: "SSH_AGENT_EXTENSION_RESPONSE"
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
}
|
||||
@@ -0,0 +1,89 @@
|
||||
import Foundation
|
||||
import AppKit
|
||||
import Security
|
||||
import SecretKit
|
||||
|
||||
/// An object responsible for generating ``SecretKit.SigningRequestProvenance`` objects.
|
||||
struct SigningRequestTracer {
|
||||
}
|
||||
|
||||
extension SigningRequestTracer {
|
||||
|
||||
/// Generates a ``SecretKit.SigningRequestProvenance`` from a ``FileHandle``.
|
||||
/// - Parameter fileHandle: The reader involved in processing the request.
|
||||
/// - Returns: A ``SecretKit.SigningRequestProvenance`` describing the origin of the request.
|
||||
func provenance(from fileHandle: FileHandle) -> SigningRequestProvenance {
|
||||
let firstInfo = process(from: fileHandle.pidOfConnectedProcess)
|
||||
var provenance = SigningRequestProvenance(root: firstInfo)
|
||||
while NSRunningApplication(processIdentifier: provenance.origin.pid) == nil && provenance.origin.parentPID != nil {
|
||||
provenance.chain.append(process(from: provenance.origin.parentPID!))
|
||||
}
|
||||
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 = unsafe MemoryLayout<kinfo_proc>.size
|
||||
let infoPointer = UnsafeMutableRawPointer.allocate(byteCount: len, alignment: 1)
|
||||
var name: [Int32] = [CTL_KERN, KERN_PROC, KERN_PROC_PID, pid]
|
||||
unsafe sysctl(&name, UInt32(name.count), infoPointer, &len, nil, 0)
|
||||
return unsafe 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 = unsafe pidAndNameInfo.kp_eproc.e_ppid != 0 ? pidAndNameInfo.kp_eproc.e_ppid : nil
|
||||
let procName = unsafe withUnsafeMutablePointer(to: &pidAndNameInfo.kp_proc.p_comm.0) { pointer in
|
||||
unsafe String(cString: pointer)
|
||||
}
|
||||
|
||||
let pathPointer = UnsafeMutablePointer<UInt8>.allocate(capacity: Int(MAXPATHLEN))
|
||||
_ = unsafe proc_pidpath(pid, pathPointer, UInt32(MAXPATHLEN))
|
||||
let path = unsafe String(cString: pathPointer)
|
||||
var secCode: Unmanaged<SecCode>!
|
||||
let flags: SecCSFlags = [.considerExpiration, .enforceRevocationChecks]
|
||||
unsafe SecCodeCreateWithPID(pid, SecCSFlags(), &secCode)
|
||||
let valid = unsafe SecCodeCheckValidity(secCode.takeRetainedValue(), flags, nil) == errSecSuccess
|
||||
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 {
|
||||
let temporaryURL = URL(fileURLWithPath: (NSTemporaryDirectory() as NSString).appendingPathComponent("\(app.bundleIdentifier ?? UUID().uuidString).png"))
|
||||
if FileManager.default.fileExists(atPath: temporaryURL.path) {
|
||||
return temporaryURL
|
||||
}
|
||||
let bitmap = NSBitmapImageRep(data: icon)
|
||||
try bitmap?.representation(using: .png, properties: [:])?.write(to: temporaryURL)
|
||||
return temporaryURL
|
||||
}
|
||||
} catch {
|
||||
}
|
||||
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
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
// from libproc.h
|
||||
@_silgen_name("proc_pidpath")
|
||||
@discardableResult func proc_pidpath(_ pid: Int32, _ buffer: UnsafeMutableRawPointer!, _ buffersize: UInt32) -> Int32
|
||||
|
||||
//// from SecTask.h
|
||||
@_silgen_name("SecCodeCreateWithPID")
|
||||
@discardableResult func SecCodeCreateWithPID(_: Int32, _: SecCSFlags, _: UnsafeMutablePointer<Unmanaged<SecCode>?>!) -> OSStatus
|
||||
22
Sources/Packages/Sources/SecretAgentKit/SigningWitness.swift
Normal file
@@ -0,0 +1,22 @@
|
||||
import Foundation
|
||||
import SecretKit
|
||||
|
||||
/// A protocol that allows conformers to be notified of access to secrets, and optionally prevent access.
|
||||
public protocol SigningWitness: Sendable {
|
||||
|
||||
/// A ridiculously named method that notifies the callee that a signing operation is about to be performed using a secret. The callee may `throw` an `Error` to prevent access from occurring.
|
||||
/// - Parameters:
|
||||
/// - 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) async throws
|
||||
|
||||
/// Notifies the callee that a signing operation has been performed for a given secret.
|
||||
/// - Parameters:
|
||||
/// - secret: The `Secret` that will was used to sign the request.
|
||||
/// - store: The `Store` that signed the request..
|
||||
/// - provenance: A `SigningRequestProvenance` object describing the origin of the request.
|
||||
func witness(accessTo secret: AnySecret, from store: AnySecretStore, by provenance: SigningRequestProvenance) async throws
|
||||
|
||||
}
|
||||
154
Sources/Packages/Sources/SecretAgentKit/SocketController.swift
Normal file
@@ -0,0 +1,154 @@
|
||||
import Foundation
|
||||
import OSLog
|
||||
import SecretKit
|
||||
|
||||
/// A controller that manages socket configuration and request dispatching.
|
||||
public struct SocketController {
|
||||
|
||||
/// A stream of Sessions. Each session represents one connection to a class communicating with the socket. Multiple Sessions may be active simultaneously.
|
||||
public let sessions: AsyncStream<Session>
|
||||
|
||||
/// A continuation to create new sessions.
|
||||
private let sessionsContinuation: AsyncStream<Session>.Continuation
|
||||
|
||||
/// The active SocketPort. Must be retained to be kept valid.
|
||||
private let port: SocketPort
|
||||
|
||||
/// The FileHandle for the main socket.
|
||||
private let fileHandle: FileHandle
|
||||
|
||||
/// Logger for the socket controller.
|
||||
private let logger = Logger(subsystem: "com.maxgoedjen.secretive.secretagent", category: "SocketController")
|
||||
|
||||
/// Tracer which determines who originates a socket connection.
|
||||
private let requestTracer = SigningRequestTracer()
|
||||
|
||||
/// Initializes a socket controller with a specified path.
|
||||
/// - Parameter path: The path to use as a socket.
|
||||
public init(path: String) {
|
||||
(sessions, sessionsContinuation) = AsyncStream<Session>.makeStream()
|
||||
logger.debug("Socket controller setting up at \(path)")
|
||||
if let _ = try? FileManager.default.removeItem(atPath: path) {
|
||||
logger.debug("Socket controller removed existing socket")
|
||||
}
|
||||
let exists = FileManager.default.fileExists(atPath: path)
|
||||
assert(!exists)
|
||||
logger.debug("Socket controller path is clear")
|
||||
port = SocketPort(path: path)
|
||||
fileHandle = FileHandle(fileDescriptor: port.socket, closeOnDealloc: true)
|
||||
Task { [fileHandle, sessionsContinuation, logger] in
|
||||
for await notification in NotificationCenter.default.notifications(named: .NSFileHandleConnectionAccepted) {
|
||||
logger.debug("Socket controller accepted connection")
|
||||
guard let new = notification.userInfo?[NSFileHandleNotificationFileHandleItem] as? FileHandle else { continue }
|
||||
let session = Session(fileHandle: new)
|
||||
sessionsContinuation.yield(session)
|
||||
await fileHandle.acceptConnectionInBackgroundAndNotifyOnMainActor()
|
||||
}
|
||||
}
|
||||
fileHandle.acceptConnectionInBackgroundAndNotify(forModes: [RunLoop.Mode.common])
|
||||
logger.debug("Socket listening at \(path)")
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
extension SocketController {
|
||||
|
||||
/// A session represents a connection that has been established between the two ends of the socket.
|
||||
public struct Session: Sendable {
|
||||
|
||||
/// Data received by the socket.
|
||||
public let messages: AsyncStream<Data>
|
||||
|
||||
/// The provenance of the process that established the session.
|
||||
public let provenance: SigningRequestProvenance
|
||||
|
||||
/// A FileHandle used to communicate with the socket.
|
||||
private let fileHandle: FileHandle
|
||||
|
||||
/// A continuation for issuing new messages.
|
||||
private let messagesContinuation: AsyncStream<Data>.Continuation
|
||||
|
||||
/// A logger for the session.
|
||||
private let logger = Logger(subsystem: "com.maxgoedjen.secretive.secretagent", category: "Session")
|
||||
|
||||
/// Initializes a new Session.
|
||||
/// - Parameter fileHandle: The FileHandle used to communicate with the socket.
|
||||
init(fileHandle: FileHandle) {
|
||||
self.fileHandle = fileHandle
|
||||
provenance = SigningRequestTracer().provenance(from: fileHandle)
|
||||
(messages, messagesContinuation) = AsyncStream.makeStream()
|
||||
Task { [messagesContinuation, logger] in
|
||||
for await _ in NotificationCenter.default.notifications(named: .NSFileHandleDataAvailable, object: fileHandle) {
|
||||
let data = fileHandle.availableData
|
||||
guard !data.isEmpty else {
|
||||
logger.debug("Socket controller received empty data, ending continuation.")
|
||||
messagesContinuation.finish()
|
||||
try fileHandle.close()
|
||||
return
|
||||
}
|
||||
messagesContinuation.yield(data)
|
||||
logger.debug("Socket controller yielded data.")
|
||||
}
|
||||
}
|
||||
Task {
|
||||
await fileHandle.waitForDataInBackgroundAndNotifyOnMainActor()
|
||||
}
|
||||
}
|
||||
|
||||
/// Writes new data to the socket.
|
||||
/// - Parameter data: The data to write.
|
||||
public func write(_ data: Data) async throws {
|
||||
try fileHandle.write(contentsOf: data)
|
||||
await fileHandle.waitForDataInBackgroundAndNotifyOnMainActor()
|
||||
}
|
||||
|
||||
/// Closes the socket and cleans up resources.
|
||||
public func close() throws {
|
||||
logger.debug("Session closed.")
|
||||
messagesContinuation.finish()
|
||||
try fileHandle.close()
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
private extension FileHandle {
|
||||
|
||||
/// Ensures waitForDataInBackgroundAndNotify will be called on the main actor.
|
||||
@MainActor func waitForDataInBackgroundAndNotifyOnMainActor() {
|
||||
waitForDataInBackgroundAndNotify()
|
||||
}
|
||||
|
||||
|
||||
/// Ensures acceptConnectionInBackgroundAndNotify will be called on the main actor.
|
||||
/// - Parameter modes: the runloop modes to use.
|
||||
@MainActor func acceptConnectionInBackgroundAndNotifyOnMainActor(forModes modes: [RunLoop.Mode]? = [RunLoop.Mode.common]) {
|
||||
acceptConnectionInBackgroundAndNotify(forModes: modes)
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
private extension SocketPort {
|
||||
|
||||
convenience init(path: String) {
|
||||
var addr = sockaddr_un()
|
||||
|
||||
let length = unsafe withUnsafeMutablePointer(to: &addr.sun_path.0) { pointer in
|
||||
unsafe path.withCString { cstring in
|
||||
let len = unsafe strlen(cstring)
|
||||
unsafe strncpy(pointer, cstring, len)
|
||||
return len
|
||||
}
|
||||
}
|
||||
// This doesn't seem to be _strictly_ neccessary with SocketPort.
|
||||
// but just for good form.
|
||||
addr.sun_family = sa_family_t(AF_UNIX)
|
||||
// This mirrors the SUN_LEN macro format.
|
||||
addr.sun_len = UInt8(MemoryLayout<sockaddr_un>.size - MemoryLayout.size(ofValue: addr.sun_path) + length)
|
||||
|
||||
let data = unsafe Data(bytes: &addr, count: MemoryLayout<sockaddr_un>.size)
|
||||
self.init(protocolFamily: AF_UNIX, socketType: SOCK_STREAM, protocol: 0, address: data)!
|
||||
}
|
||||
|
||||
}
|
||||
@@ -0,0 +1,40 @@
|
||||
# ``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
|
||||
|
||||
- ``OpenSSHPublicKeyWriter``
|
||||
- ``OpenSSHReader``
|
||||
|
||||
### Signing Process
|
||||
|
||||
- ``SigningRequestProvenance``
|
||||
|
||||
### Authentication Persistence
|
||||
|
||||
- ``PersistedAuthenticationContext``
|
||||
|
||||
### Errors
|
||||
|
||||
- ``KeychainError``
|
||||
- ``SigningError``
|
||||
- ``SecurityError``
|
||||
56
Sources/Packages/Sources/SecretKit/Erasers/AnySecret.swift
Normal file
@@ -0,0 +1,56 @@
|
||||
import Foundation
|
||||
|
||||
/// Type eraser for Secret.
|
||||
public struct AnySecret: Secret, @unchecked Sendable {
|
||||
|
||||
public let base: any Secret
|
||||
private let _id: () -> AnyHashable
|
||||
private let _name: () -> String
|
||||
private let _publicKey: () -> Data
|
||||
private let _attributes: () -> Attributes
|
||||
private let _eq: (AnySecret) -> Bool
|
||||
|
||||
public init<T>(_ secret: T) where T: Secret {
|
||||
if let secret = secret as? AnySecret {
|
||||
base = secret.base
|
||||
_id = secret._id
|
||||
_name = secret._name
|
||||
_publicKey = secret._publicKey
|
||||
_attributes = secret._attributes
|
||||
_eq = secret._eq
|
||||
} else {
|
||||
base = secret
|
||||
_id = { secret.id as AnyHashable }
|
||||
_name = { secret.name }
|
||||
_publicKey = { secret.publicKey }
|
||||
_attributes = { secret.attributes }
|
||||
_eq = { secret == $0.base as? T }
|
||||
}
|
||||
}
|
||||
|
||||
public var id: AnyHashable {
|
||||
_id()
|
||||
}
|
||||
|
||||
public var name: String {
|
||||
_name()
|
||||
}
|
||||
|
||||
public var publicKey: Data {
|
||||
_publicKey()
|
||||
}
|
||||
|
||||
public var attributes: Attributes {
|
||||
_attributes()
|
||||
}
|
||||
|
||||
public static func == (lhs: AnySecret, rhs: AnySecret) -> Bool {
|
||||
lhs._eq(rhs)
|
||||
}
|
||||
|
||||
public func hash(into hasher: inout Hasher) {
|
||||
id.hash(into: &hasher)
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
@@ -0,0 +1,94 @@
|
||||
import Foundation
|
||||
|
||||
/// Type eraser for SecretStore.
|
||||
open class AnySecretStore: SecretStore, @unchecked Sendable {
|
||||
|
||||
let base: any SecretStore
|
||||
private let _isAvailable: @MainActor @Sendable () -> Bool
|
||||
private let _id: @Sendable () -> UUID
|
||||
private let _name: @MainActor @Sendable () -> String
|
||||
private let _secrets: @MainActor @Sendable () -> [AnySecret]
|
||||
private let _sign: @Sendable (Data, AnySecret, SigningRequestProvenance) async throws -> Data
|
||||
private let _existingPersistedAuthenticationContext: @Sendable (AnySecret) async -> PersistedAuthenticationContext?
|
||||
private let _persistAuthentication: @Sendable (AnySecret, TimeInterval) async throws -> Void
|
||||
private let _reloadSecrets: @Sendable () async -> Void
|
||||
|
||||
public init<SecretStoreType>(_ secretStore: SecretStoreType) where SecretStoreType: SecretStore {
|
||||
base = secretStore
|
||||
_isAvailable = { secretStore.isAvailable }
|
||||
_name = { secretStore.name }
|
||||
_id = { secretStore.id }
|
||||
_secrets = { secretStore.secrets.map { AnySecret($0) } }
|
||||
_sign = { try await secretStore.sign(data: $0, with: $1.base as! SecretStoreType.SecretType, for: $2) }
|
||||
_existingPersistedAuthenticationContext = { await secretStore.existingPersistedAuthenticationContext(secret: $0.base as! SecretStoreType.SecretType) }
|
||||
_persistAuthentication = { try await secretStore.persistAuthentication(secret: $0.base as! SecretStoreType.SecretType, forDuration: $1) }
|
||||
_reloadSecrets = { await secretStore.reloadSecrets() }
|
||||
}
|
||||
|
||||
@MainActor public var isAvailable: Bool {
|
||||
return _isAvailable()
|
||||
}
|
||||
|
||||
public var id: UUID {
|
||||
return _id()
|
||||
}
|
||||
|
||||
@MainActor public var name: String {
|
||||
return _name()
|
||||
}
|
||||
|
||||
@MainActor public var secrets: [AnySecret] {
|
||||
return _secrets()
|
||||
}
|
||||
|
||||
public func sign(data: Data, with secret: AnySecret, for provenance: SigningRequestProvenance) async throws -> Data {
|
||||
try await _sign(data, secret, provenance)
|
||||
}
|
||||
|
||||
public func existingPersistedAuthenticationContext(secret: AnySecret) async -> PersistedAuthenticationContext? {
|
||||
await _existingPersistedAuthenticationContext(secret)
|
||||
}
|
||||
|
||||
public func persistAuthentication(secret: AnySecret, forDuration duration: TimeInterval) async throws {
|
||||
try await _persistAuthentication(secret, duration)
|
||||
}
|
||||
|
||||
public func reloadSecrets() async {
|
||||
await _reloadSecrets()
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
public final class AnySecretStoreModifiable: AnySecretStore, SecretStoreModifiable, @unchecked Sendable {
|
||||
|
||||
private let _create: @Sendable (String, Attributes) async throws -> AnySecret
|
||||
private let _delete: @Sendable (AnySecret) async throws -> Void
|
||||
private let _update: @Sendable (AnySecret, String, Attributes) async throws -> Void
|
||||
private let _supportedKeyTypes: @Sendable () -> KeyAvailability
|
||||
|
||||
public init<SecretStoreType>(_ secretStore: SecretStoreType) where SecretStoreType: SecretStoreModifiable {
|
||||
_create = { AnySecret(try await secretStore.create(name: $0, attributes: $1)) }
|
||||
_delete = { try await secretStore.delete(secret: $0.base as! SecretStoreType.SecretType) }
|
||||
_update = { try await secretStore.update(secret: $0.base as! SecretStoreType.SecretType, name: $1, attributes: $2) }
|
||||
_supportedKeyTypes = { secretStore.supportedKeyTypes }
|
||||
super.init(secretStore)
|
||||
}
|
||||
|
||||
@discardableResult
|
||||
public func create(name: String, attributes: Attributes) async throws -> SecretType {
|
||||
try await _create(name, attributes)
|
||||
}
|
||||
|
||||
public func delete(secret: AnySecret) async throws {
|
||||
try await _delete(secret)
|
||||
}
|
||||
|
||||
public func update(secret: AnySecret, name: String, attributes: Attributes) async throws {
|
||||
try await _update(secret, name, attributes)
|
||||
}
|
||||
|
||||
public var supportedKeyTypes: KeyAvailability {
|
||||
_supportedKeyTypes()
|
||||
}
|
||||
|
||||
}
|
||||
69
Sources/Packages/Sources/SecretKit/KeychainTypes.swift
Normal file
@@ -0,0 +1,69 @@
|
||||
import Foundation
|
||||
|
||||
public typealias SecurityError = Unmanaged<CFError>
|
||||
|
||||
/// Wraps a Swift dictionary in a CFDictionary.
|
||||
/// - Parameter dictionary: The Swift dictionary to wrap.
|
||||
/// - Returns: A CFDictionary containing the keys and values.
|
||||
public func KeychainDictionary(_ dictionary: [CFString: Any]) -> CFDictionary {
|
||||
dictionary as CFDictionary
|
||||
}
|
||||
|
||||
public extension CFError {
|
||||
|
||||
/// The CFError returned when a verification operation fails.
|
||||
static let verifyError = CFErrorCreate(nil, NSOSStatusErrorDomain as CFErrorDomain, CFIndex(errSecVerifyFailed), nil)!
|
||||
|
||||
/// Equality operation that only considers domain and code.
|
||||
static func ~=(lhs: CFError, rhs: CFError) -> Bool {
|
||||
CFErrorGetDomain(lhs) == CFErrorGetDomain(rhs) && CFErrorGetCode(lhs) == CFErrorGetCode(rhs)
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
/// A wrapper around an error code reported by a Keychain API.
|
||||
public struct KeychainError: Error {
|
||||
/// The status code involved, if one was reported.
|
||||
public let statusCode: OSStatus?
|
||||
|
||||
/// Initializes a KeychainError with an optional error code.
|
||||
/// - Parameter statusCode: The status code returned by the keychain operation, if one is applicable.
|
||||
public init(statusCode: OSStatus?) {
|
||||
self.statusCode = statusCode
|
||||
}
|
||||
}
|
||||
|
||||
/// A signing-related error.
|
||||
public struct SigningError: Error {
|
||||
/// The underlying error reported by the API, if one was returned.
|
||||
public let error: CFError?
|
||||
|
||||
/// Initializes a SigningError with an optional SecurityError.
|
||||
/// - Parameter statusCode: The SecurityError, if one is applicable.
|
||||
public init(error: SecurityError?) {
|
||||
self.error = unsafe error?.takeRetainedValue()
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
public extension SecretStore {
|
||||
|
||||
/// Returns the appropriate keychian signature algorithm to use for a given secret.
|
||||
/// - Parameters:
|
||||
/// - secret: The secret which will be used for signing.
|
||||
/// - Returns: The appropriate algorithm.
|
||||
func signatureAlgorithm(for secret: SecretType) -> SecKeyAlgorithm? {
|
||||
switch secret.keyType {
|
||||
case .ecdsa256:
|
||||
.ecdsaSignatureMessageX962SHA256
|
||||
case .ecdsa384:
|
||||
.ecdsaSignatureMessageX962SHA384
|
||||
case .rsa2048:
|
||||
.rsaSignatureMessagePKCS1v15SHA512
|
||||
default:
|
||||
nil
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
}
|
||||