~ knotless Search/
↑↓ move↵ open⇧↵ all results

chadtmiller.com/knotless

git that lives in your Atmosphere account

knotless.dev
1 collaborator

knotless 0.18.0 Latest 2 packages, 1 image

1
10
50 lines · 2.0 KB Raw History
import CryptoKit
import Foundation
import Security

/// The key this device gives the server to seal a private repository's
/// notifications with, which Apple passes on but can't read. It's in the
/// keychain, in a group the app shares with its notification extension
/// alone, which opens them before they show.
enum PushKey {
    private static var query: [String: Any] {
        var query: [String: Any] = [
            kSecClass as String: kSecClassGenericPassword,
            kSecAttrService as String: "dev.knotless.app",
            kSecAttrAccount as String: "push-key",
        ]
        // `$(AppIdentifierPrefix)dev.knotless.shared`, as project.yml puts it in each Info.plist.
        if let group = Bundle.main.object(forInfoDictionaryKey: "KnotlessKeychainGroup") as? String {
            query[kSecAttrAccessGroup as String] = group
        }
        return query
    }

    /// The key kept, if there is one.
    static var kept: SymmetricKey? {
        var ask = query
        ask[kSecReturnData as String] = true
        var found: CFTypeRef?
        guard SecItemCopyMatching(ask as CFDictionary, &found) == errSecSuccess,
              let data = found as? Data, data.count == 32
        else { return nil }
        return SymmetricKey(data: data)
    }

    /// The key, made and kept the first time, in base64 as the server takes it:
    /// nil if it can't be kept, and the server then seals nothing.
    static func base64() -> String? {
        if let kept { return encoded(kept) }
        let key = SymmetricKey(size: .bits256)
        var item = query
        item[kSecValueData as String] = key.withUnsafeBytes { Data($0) }
        // The extension opens a notification on a locked phone.
        item[kSecAttrAccessible as String] = kSecAttrAccessibleAfterFirstUnlockThisDeviceOnly
        guard SecItemAdd(item as CFDictionary, nil) == errSecSuccess else { return nil }
        return encoded(key)
    }

    private static func encoded(_ key: SymmetricKey) -> String {
        key.withUnsafeBytes { Data($0) }.base64EncodedString()
    }
}