Sources/OrgApp/LicenseKey.swift
120 lines · 5794 bytes
1import CryptoKit
2import Foundation
3
4/// A Mac license key: `ORGSTAR1-<payload>.<signature>`, both base64url. The payload is JSON the
5/// license issuer (`packaging/license-issuer`) signs with Ed25519; the app checks the signature
6/// offline against `publicKey`.
7public struct LicenseKey: Codable, Sendable, Equatable {
8 /// Who the license is for: the sponsor's GitHub login.
9 public let holder: String
10 /// The sponsoring account, `github:<node ID>`.
11 public let transaction: String
12 /// When the key was issued, as Unix seconds.
13 public let issued: Int
14 /// When a monthly sponsor's key stops working, as Unix seconds; nil for a lifetime key.
15 public let expires: Int?
16
17 enum CodingKeys: String, CodingKey {
18 case holder = "e", transaction = "t", issued = "i", expires = "x"
19 }
20
21 public enum Failure: Error, Equatable {
22 case malformed, badSignature, expired
23 }
24
25 static let prefix = "ORGSTAR1-"
26
27 /// The issuer's Ed25519 public key (raw, 32 bytes), base64. `packaging/license-issuer/keygen.sh`
28 /// writes it here; until then it is a placeholder whose private half was discarded, and
29 /// `scripts/release-mac.sh` refuses to build.
30 public static let publicKey = "bsxWsmNYsFJiN6e/UaBgRzAmHBry9+sjI8BFFbf21aM="
31
32 public init(holder: String, transaction: String, issued: Int, expires: Int? = nil) {
33 self.holder = holder
34 self.transaction = transaction
35 self.issued = issued
36 self.expires = expires
37 }
38
39 public func isExpired(at now: Date = .now) -> Bool {
40 expires.map { now.timeIntervalSince1970 >= Double($0) } ?? false
41 }
42
43 /// Checks `text` (whitespace and line breaks from pasting are ignored) and returns the license.
44 public static func verify(_ text: String, publicKey: String = publicKey) throws(Failure) -> LicenseKey {
45 let key = text.filter { !$0.isWhitespace }
46 guard key.hasPrefix(prefix) else { throw .malformed }
47 let parts = key.dropFirst(prefix.count).split(separator: ".", omittingEmptySubsequences: false)
48 guard parts.count == 2,
49 let payload = Data(base64URL: String(parts[0])),
50 let signature = Data(base64URL: String(parts[1])),
51 let raw = Data(base64Encoded: publicKey),
52 let signer = try? Curve25519.Signing.PublicKey(rawRepresentation: raw)
53 else { throw .malformed }
54 guard signer.isValidSignature(signature, for: payload) else { throw .badSignature }
55 guard let license = try? JSONDecoder().decode(LicenseKey.self, from: payload) else { throw .malformed }
56 return license
57 }
58}
59
60/// The Mac app's stored license.
61public enum LicenseStore {
62 static let key = "pro.licenseKey"
63 /// Where a monthly key is exchanged for a fresh one while the sponsorship lasts.
64 static let renewURL = URL(string: "https://krz.sh/apps/orgstar/renew")!
65 /// A monthly key is renewed once fewer days than this are left (the issuer gives 40).
66 static let renewWithin: TimeInterval = 30 * 86400
67
68 /// The stored key's license, if it verifies and hasn't expired.
69 public static func current(defaults: UserDefaults = .standard, now: Date = .now, publicKey: String = LicenseKey.publicKey) -> LicenseKey? {
70 stored(defaults: defaults, publicKey: publicKey).flatMap { $0.isExpired(at: now) ? nil : $0 }
71 }
72
73 /// The stored key's license, expired or not.
74 static func stored(defaults: UserDefaults, publicKey: String) -> LicenseKey? {
75 defaults.string(forKey: key).flatMap { try? LicenseKey.verify($0, publicKey: publicKey) }
76 }
77
78 /// Exchanges a monthly key that is due for a fresh one. Returns whether the stored key
79 /// changed. A refusal (the sponsorship ended) or no network leaves the key to expire.
80 public static func renewIfDue(
81 defaults: UserDefaults = .standard, now: Date = .now, publicKey: String = LicenseKey.publicKey,
82 post: (URLRequest) async throws -> (Data, URLResponse) = { try await URLSession.shared.data(for: $0) }
83 ) async -> Bool {
84 guard let text = defaults.string(forKey: key), let license = try? LicenseKey.verify(text, publicKey: publicKey),
85 let expires = license.expires, Double(expires) - now.timeIntervalSince1970 < renewWithin
86 else { return false }
87 var request = URLRequest(url: renewURL)
88 request.httpMethod = "POST"
89 request.httpBody = Data(text.utf8)
90 guard let (data, response) = try? await post(request), (response as? HTTPURLResponse)?.statusCode == 200,
91 let fresh = String(data: data, encoding: .utf8)?.filter({ !$0.isWhitespace }),
92 let renewed = try? LicenseKey.verify(fresh, publicKey: publicKey), renewed.transaction == license.transaction,
93 (renewed.expires ?? .max) > expires
94 else { return false }
95 defaults.set(fresh, forKey: key)
96 return true
97 }
98
99 /// Verifies and stores `text`.
100 public static func activate(
101 _ text: String, defaults: UserDefaults = .standard, now: Date = .now, publicKey: String = LicenseKey.publicKey
102 ) throws(LicenseKey.Failure) -> LicenseKey {
103 let license = try LicenseKey.verify(text, publicKey: publicKey)
104 guard !license.isExpired(at: now) else { throw .expired }
105 defaults.set(text.filter { !$0.isWhitespace }, forKey: key)
106 return license
107 }
108
109 public static func remove(defaults: UserDefaults = .standard) {
110 defaults.removeObject(forKey: key)
111 }
112}
113
114extension Data {
115 init?(base64URL: String) {
116 var text = base64URL.replacingOccurrences(of: "-", with: "+").replacingOccurrences(of: "_", with: "/")
117 text += String(repeating: "=", count: (4 - text.count % 4) % 4)
118 self.init(base64Encoded: text)
119 }
120}