~ 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
38 lines · 1.9 KB Raw History
import CryptoKit
import Foundation
import UserNotifications

/// Opens what the server sealed in a private repository's notification with
/// this device's key (`PushKey`), so it shows as any other does, and taps
/// through to its thread. One it can't open shows as it came: that there is
/// new activity, and nothing more.
final class NotificationService: UNNotificationServiceExtension {
    override func didReceive(
        _ request: UNNotificationRequest,
        withContentHandler contentHandler: @escaping (UNNotificationContent) -> Void
    ) {
        contentHandler(Self.opened(request.content) ?? request.content)
    }

    /// `content` as the server sealed it in: AES-256-GCM, its nonce first, of
    /// the notification it would send for a public repository.
    static func opened(_ content: UNNotificationContent) -> UNNotificationContent? {
        guard let sealed = content.userInfo["sealed"] as? String,
              let data = Data(base64Encoded: sealed),
              let key = PushKey.kept,
              let box = try? AES.GCM.SealedBox(combined: data),
              let plain = try? AES.GCM.open(box, using: key),
              var message = (try? JSONSerialization.jsonObject(with: plain)) as? [String: Any],
              let aps = message.removeValue(forKey: "aps") as? [String: Any],
              let alert = aps["alert"] as? [String: Any],
              let shown = content.mutableCopy() as? UNMutableNotificationContent
        else { return nil }
        shown.title = alert["title"] as? String ?? shown.title
        shown.subtitle = alert["subtitle"] as? String ?? ""
        shown.body = alert["body"] as? String ?? shown.body
        if let thread = aps["thread-id"] as? String { shown.threadIdentifier = thread }
        // Where a tap leads (`PushTarget`): its subject, repository and author.
        shown.userInfo = message
        return shown
    }
}