Commit d8907828b9

d8907828b90029789c777b566de52ad9944d04cb

parent: 41729a920c

Verified · cmc

cmc <hello@cleberg.net> · 2026-11-20 01:50 UTC

orgstar+ for Mac through GitHub Sponsors

- License Worker: Paddle replaced by Sign in with GitHub. A one-time
  sponsorship of $60 or more gets a key that doesn't expire; an active
  monthly one of $5 or more gets a key that expires after 40 days.
  POST /renew exchanges a monthly key for a fresh one while the
  sponsorship is active. Node tests in worker.test.mjs.
- LicenseKey: holder (GitHub login) and optional expiry "x". Expired
  keys don't unlock and can't be activated; LicenseStore.renewIfDue
  renews a monthly key within 30 days of expiry, daily from launch.
- License form and paywall: sponsor and get-key links, monthly status.
- README and CONTRIBUTING: pricing and Worker setup.
- l10n: five new strings in de, fr, ja, es and pt-BR.

Layout: unified · split

CONTRIBUTING.org +20
@@ -67,6 +67,26 @@ and availability, and a review screenshot of the About screen's Support Developm
67Submit new in-app purchases with an app version. Changes take up to an hour to reach the 67Submit new in-app purchases with an app version. Changes take up to an hour to reach the
68sandbox; test there with a Sandbox Apple Account (Settings ▸ Developer on the device). 68sandbox; test there with a Sandbox Apple Account (Settings ▸ Developer on the device).
69 69
70* Mac licenses
71
72orgstar+ for Mac comes with GitHub Sponsors: $60 once for a key that doesn't expire, or $5 a
73month for a key that expires after 40 days and that the app renews daily from 30 days before.
74=packaging/license-issuer= is the Cloudflare Worker that serves =krz.sh/apps/orgstar/buy=,
75=/license= (Sign in with GitHub, then the key) and =/renew=; its header describes the key
76format.
77
78Setup, once:
79- In GitHub Sponsors, publish a $60 one-time tier and a $5 monthly tier.
80- Create a GitHub OAuth app with the callback URL =https://krz.sh/apps/orgstar/license= and
81 put its client ID in =GITHUB_CLIENT_ID= in =wrangler.toml=.
82- =npx wrangler secret put GITHUB_CLIENT_SECRET= with the OAuth app's secret, and
83 =GITHUB_TOKEN= with a token of the sponsored account (=read:user=), which renewals use.
84- =packaging/license-issuer/keygen.sh= set =LICENSE_PRIVATE_KEY= and the app's public key.
85 Running it again invalidates every key issued so far.
86
87=node --test packaging/license-issuer= runs the Worker's tests; =npx wrangler deploy= from
88that folder publishes it.
89
70* Tests 90* Tests
71 91
72#+BEGIN_SRC sh 92#+BEGIN_SRC sh
README.org +3 −2
@@ -67,8 +67,9 @@ backlinks; widgets, the Apple Watch app and the clock Live Activity; Calendar an
67the agenda; and Shortcuts actions. 67the agenda; and Shortcuts actions.
68 68
69- iPhone and iPad: in-app, $1.99 a month, $19.99 a year or $39.99 once. 69- iPhone and iPad: in-app, $1.99 a month, $19.99 a year or $39.99 once.
70- Mac: $39.99 once, for a license key from [[https://krz.sh/apps/orgstar/buy][krz.sh/apps/orgstar/buy]], entered in 70- Mac: by [[https://github.com/sponsors/ccleberg][sponsoring on GitHub]], $60 once for a license key that doesn't expire,
71 Settings ▸ orgstar+. 71 or $5 a month for a key orgstar renews while you sponsor. Sign in with GitHub at
72 [[https://krz.sh/apps/orgstar/license][krz.sh/apps/orgstar/license]] for the key and enter it in Settings ▸ orgstar+.
72 73
73Anyone who installed orgstar before orgstar+ keeps every feature without buying it. 74Anyone who installed orgstar before orgstar+ keeps every feature without buying it.
74 75
Sources/OrgApp/LicenseKey.swift +54 −13
@@ -2,21 +2,24 @@ import CryptoKit
2import Foundation 2import Foundation
3 3
4/// A Mac license key: `ORGSTAR1-<payload>.<signature>`, both base64url. The payload is JSON the 4/// A Mac license key: `ORGSTAR1-<payload>.<signature>`, both base64url. The payload is JSON the
5/// license issuer signs with Ed25519; the app checks the signature offline against `publicKey`. 5/// license issuer (`packaging/license-issuer`) signs with Ed25519; the app checks the signature
6/// offline against `publicKey`.
6public struct LicenseKey: Codable, Sendable, Equatable { 7public struct LicenseKey: Codable, Sendable, Equatable {
7 /// The email the license was sold to. 8 /// Who the license is for: the sponsor's GitHub login.
8 public let email: String 9 public let holder: String
9 /// The payment provider's transaction ID. 10 /// The sponsoring account, `github:<node ID>`.
10 public let transaction: String 11 public let transaction: String
11 /// When the key was issued, as Unix seconds. 12 /// When the key was issued, as Unix seconds.
12 public let issued: Int 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?
13 16
14 enum CodingKeys: String, CodingKey { 17 enum CodingKeys: String, CodingKey {
15 case email = "e", transaction = "t", issued = "i" 18 case holder = "e", transaction = "t", issued = "i", expires = "x"
16 } 19 }
17 20
18 public enum Failure: Error, Equatable { 21 public enum Failure: Error, Equatable {
19 case malformed, badSignature 22 case malformed, badSignature, expired
20 } 23 }
21 24
22 static let prefix = "ORGSTAR1-" 25 static let prefix = "ORGSTAR1-"
@@ -26,10 +29,15 @@ public struct LicenseKey: Codable, Sendable, Equatable {
26 /// `scripts/release-mac.sh` refuses to build. 29 /// `scripts/release-mac.sh` refuses to build.
27 public static let publicKey = "bsxWsmNYsFJiN6e/UaBgRzAmHBry9+sjI8BFFbf21aM=" 30 public static let publicKey = "bsxWsmNYsFJiN6e/UaBgRzAmHBry9+sjI8BFFbf21aM="
28 31
29 public init(email: String, transaction: String, issued: Int) { 32 public init(holder: String, transaction: String, issued: Int, expires: Int? = nil) {
30 self.email = email 33 self.holder = holder
31 self.transaction = transaction 34 self.transaction = transaction
32 self.issued = issued 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
33 } 41 }
34 42
35 /// Checks `text` (whitespace and line breaks from pasting are ignored) and returns the license. 43 /// Checks `text` (whitespace and line breaks from pasting are ignored) and returns the license.
@@ -52,15 +60,48 @@ public struct LicenseKey: Codable, Sendable, Equatable {
52/// The Mac app's stored license. 60/// The Mac app's stored license.
53public enum LicenseStore { 61public enum LicenseStore {
54 static let key = "pro.licenseKey" 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 }
55 77
56 /// The stored key's license, if it still verifies. 78 /// Exchanges a monthly key that is due for a fresh one. Returns whether the stored key
57 public static func current(defaults: UserDefaults = .standard) -> LicenseKey? { 79 /// changed. A refusal (the sponsorship ended) or no network leaves the key to expire.
58 defaults.string(forKey: key).flatMap { try? LicenseKey.verify($0) } 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
59 } 97 }
60 98
61 /// Verifies and stores `text`. 99 /// Verifies and stores `text`.
62 public static func activate(_ text: String, defaults: UserDefaults = .standard) throws(LicenseKey.Failure) -> LicenseKey { 100 public static func activate(
63 let license = try LicenseKey.verify(text) 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 }
64 defaults.set(text.filter { !$0.isWhitespace }, forKey: key) 105 defaults.set(text.filter { !$0.isWhitespace }, forKey: key)
65 return license 106 return license
66 } 107 }
Sources/Orgstar/OrgstarApp.swift +1
@@ -325,6 +325,7 @@ struct OrgstarApp: App {
325 325
326 init() { 326 init() {
327 MacPro.resolve() 327 MacPro.resolve()
328 MacPro.renewInBackground()
328 // Debug builds, and runs with ORGSTAR_PERF set: main-thread stalls in the console. 329 // Debug builds, and runs with ORGSTAR_PERF set: main-thread stalls in the console.
329 #if DEBUG 330 #if DEBUG
330 Perf.watchMainThread() 331 Perf.watchMainThread()
Sources/Orgstar/ProLicense.swift +27 −6
@@ -1,9 +1,10 @@
1import OrgApp 1import OrgApp
2import SwiftUI 2import SwiftUI
3 3
4/// Pro on the Mac: a license key bought from the website, or an install that predates Pro. 4/// Pro on the Mac: a license key for sponsoring on GitHub, or an install that predates Pro.
5enum MacPro { 5enum MacPro {
6 static let buyURL = URL(string: "https://krz.sh/apps/orgstar/buy")! 6 static let buyURL = URL(string: "https://krz.sh/apps/orgstar/buy")!
7 static let keyURL = URL(string: "https://krz.sh/apps/orgstar/license")!
7 8
8 /// Sets `ProAccess.shared` from the stored license or an earlier free install. 9 /// Sets `ProAccess.shared` from the stored license or an earlier free install.
9 @MainActor static func resolve() { 10 @MainActor static func resolve() {
@@ -15,6 +16,18 @@ enum MacPro {
15 ProAccess.shared.set(nil) 16 ProAccess.shared.set(nil)
16 } 17 }
17 } 18 }
19
20 /// Renews a monthly sponsor's key now and then daily, and re-resolves, so an ended
21 /// sponsorship locks orgstar+ once its key expires.
22 @MainActor static func renewInBackground() {
23 Task {
24 while true {
25 _ = await LicenseStore.renewIfDue()
26 resolve()
27 try? await Task.sleep(for: .seconds(86400))
28 }
29 }
30 }
18} 31}
19 32
20/// Status, buying, and entering or removing a license key. 33/// Status, buying, and entering or removing a license key.
@@ -29,7 +42,12 @@ struct LicenseForm: View {
29 Section { 42 Section {
30 switch access.grant { 43 switch access.grant {
31 case .license: 44 case .license:
32 LabeledContent("orgstar+", value: license.map { "Licensed to \($0.email)" } ?? "Licensed") 45 LabeledContent("orgstar+", value: license.map { "Licensed to \($0.holder)" } ?? "Licensed")
46 if let expires = license?.expires {
47 let date = Date(timeIntervalSince1970: TimeInterval(expires)).formatted(date: .abbreviated, time: .omitted)
48 Text("Renews while you sponsor monthly. This key is valid until \(date).")
49 .foregroundStyle(.secondary)
50 }
33 case .grandfathered: 51 case .grandfathered:
34 LabeledContent("orgstar+", value: "Included: you used orgstar before orgstar+") 52 LabeledContent("orgstar+", value: "Included: you used orgstar before orgstar+")
35 case .purchase, nil: 53 case .purchase, nil:
@@ -44,12 +62,13 @@ struct LicenseForm: View {
44 .onSubmit(activate) 62 .onSubmit(activate)
45 if let error { Text(error).foregroundStyle(.red) } 63 if let error { Text(error).foregroundStyle(.red) }
46 HStack { 64 HStack {
47 Link("Buy orgstar+…", destination: MacPro.buyURL) 65 Link("Sponsor for orgstar+…", destination: MacPro.buyURL)
66 Link("Get Your Key…", destination: MacPro.keyURL)
48 Spacer() 67 Spacer()
49 Button("Activate", action: activate).disabled(key.trimmingCharacters(in: .whitespacesAndNewlines).isEmpty) 68 Button("Activate", action: activate).disabled(key.trimmingCharacters(in: .whitespacesAndNewlines).isEmpty)
50 } 69 }
51 } footer: { 70 } footer: {
52 Text("Your key is in the email from the purchase. It is checked on this Mac; nothing is sent.") 71 Text("Sponsors get their key by signing in with GitHub. It is checked on this Mac; a monthly sponsor's key is renewed with krz.sh.")
53 } 72 }
54 } else { 73 } else {
55 Section { 74 Section {
@@ -76,7 +95,9 @@ struct LicenseForm: View {
76 error = nil 95 error = nil
77 ProAccess.shared.set(.license) 96 ProAccess.shared.set(.license)
78 } catch .badSignature { 97 } catch .badSignature {
79 error = "This key isn't valid for orgstar. Paste the whole key from the email." 98 error = "This key isn't valid for orgstar. Paste the whole key from the license page."
99 } catch .expired {
100 error = "This key has expired. Sign in on the license page for a current one."
80 } catch { 101 } catch {
81 self.error = "That doesn't look like an orgstar license key." 102 self.error = "That doesn't look like an orgstar license key."
82 } 103 }
@@ -92,7 +113,7 @@ struct ProPaywallSheet: View {
92 VStack(alignment: .leading, spacing: 0) { 113 VStack(alignment: .leading, spacing: 0) {
93 VStack(alignment: .leading, spacing: 6) { 114 VStack(alignment: .leading, spacing: 6) {
94 Label("\(feature.title) needs orgstar+", systemImage: feature.systemImage).font(.headline) 115 Label("\(feature.title) needs orgstar+", systemImage: feature.systemImage).font(.headline)
95 Text("orgstar+ is a one-time purchase of $39.99 for this Mac. Editing, the agenda, capture, clocking and search stay free.") 116 Text("orgstar+ for Mac comes with sponsoring orgstar on GitHub: $60 once, or $5 a month. Editing, the agenda, capture, clocking and search stay free.")
96 .foregroundStyle(.secondary) 117 .foregroundStyle(.secondary)
97 } 118 }
98 .padding([.horizontal, .top], 20) 119 .padding([.horizontal, .top], 20)
Tests/OrgAppTests/ProAccessTests.swift +54 −1
@@ -84,7 +84,7 @@ struct LicenseKeyTests {
84 @Test func verifiesASignedKey() throws { 84 @Test func verifiesASignedKey() throws {
85 let text = try key(#"{"e":"a@example.com","t":"txn_01","i":1763000000}"#) 85 let text = try key(#"{"e":"a@example.com","t":"txn_01","i":1763000000}"#)
86 let license = try LicenseKey.verify(text, publicKey: publicKey) 86 let license = try LicenseKey.verify(text, publicKey: publicKey)
87 #expect(license == LicenseKey(email: "a@example.com", transaction: "txn_01", issued: 1763000000)) 87 #expect(license == LicenseKey(holder: "a@example.com", transaction: "txn_01", issued: 1763000000))
88 } 88 }
89 89
90 @Test func ignoresWhitespaceFromPasting() throws { 90 @Test func ignoresWhitespaceFromPasting() throws {
@@ -116,6 +116,59 @@ struct LicenseKeyTests {
116 _ = try Curve25519.Signing.PublicKey(rawRepresentation: raw) 116 _ = try Curve25519.Signing.PublicKey(rawRepresentation: raw)
117 } 117 }
118 118
119 @Test func monthlyKeysExpire() throws {
120 let license = try LicenseKey.verify(try key(#"{"e":"octo","t":"github:U_1","i":100,"x":200}"#), publicKey: publicKey)
121 #expect(license.expires == 200)
122 #expect(!license.isExpired(at: Date(timeIntervalSince1970: 199)))
123 #expect(license.isExpired(at: Date(timeIntervalSince1970: 200)))
124 #expect(LicenseKey(holder: "octo", transaction: "github:U_1", issued: 100).isExpired(at: .distantFuture) == false)
125 }
126
127 @Test func refusesAndIgnoresExpiredKeys() throws {
128 let defaults = try #require(UserDefaults(suiteName: "test.\(UUID().uuidString)"))
129 let text = try key(#"{"e":"octo","t":"github:U_1","i":100,"x":200}"#)
130 #expect(throws: LicenseKey.Failure.expired) {
131 try LicenseStore.activate(text, defaults: defaults, now: Date(timeIntervalSince1970: 300), publicKey: publicKey)
132 }
133 _ = try LicenseStore.activate(text, defaults: defaults, now: Date(timeIntervalSince1970: 150), publicKey: publicKey)
134 #expect(LicenseStore.current(defaults: defaults, now: Date(timeIntervalSince1970: 150), publicKey: publicKey) != nil)
135 #expect(LicenseStore.current(defaults: defaults, now: Date(timeIntervalSince1970: 300), publicKey: publicKey) == nil)
136 }
137
138 /// Stores a monthly key expiring at `expires` and renews at `now`, the issuer answering
139 /// `status` with `answer`. Returns the stored key afterwards and whether it asked.
140 func renew(expires: Int, now: Int, status: Int, answer: String) async throws -> (key: String?, asked: Bool) {
141 let defaults = try #require(UserDefaults(suiteName: "test.\(UUID().uuidString)"))
142 defaults.set(try key(#"{"e":"octo","t":"github:U_1","i":1,"x":\#(expires)}"#), forKey: LicenseStore.key)
143 nonisolated(unsafe) var asked = false
144 _ = await LicenseStore.renewIfDue(defaults: defaults, now: Date(timeIntervalSince1970: TimeInterval(now)), publicKey: publicKey) { request in
145 asked = true
146 #expect(request.httpMethod == "POST")
147 return (Data(answer.utf8), HTTPURLResponse(url: request.url!, statusCode: status, httpVersion: nil, headerFields: nil)!)
148 }
149 return (defaults.string(forKey: LicenseStore.key), asked)
150 }
151
152 @Test func renewsMonthlyKeysThatAreDue() async throws {
153 let day = 86400
154 let fresh = try key(#"{"e":"octo","t":"github:U_1","i":2,"x":\#(80 * day)}"#)
155 let renewed = try await renew(expires: 40 * day, now: 20 * day, status: 200, answer: fresh + "\n")
156 #expect(renewed.asked && renewed.key == fresh)
157
158 let early = try await renew(expires: 40 * day, now: 5 * day, status: 200, answer: fresh)
159 #expect(!early.asked)
160 }
161
162 @Test func keepsTheKeyWhenRenewalIsRefusedOrWrong() async throws {
163 let day = 86400
164 let ended = try await renew(expires: 40 * day, now: 20 * day, status: 403, answer: "The monthly sponsorship has ended.")
165 #expect(ended.asked && ended.key.flatMap { try? LicenseKey.verify($0, publicKey: publicKey).expires } == 40 * day)
166
167 let someoneElse = try key(#"{"e":"other","t":"github:U_2","i":2,"x":\#(80 * day)}"#)
168 let wrong = try await renew(expires: 40 * day, now: 20 * day, status: 200, answer: someoneElse)
169 #expect(wrong.key.flatMap { try? LicenseKey.verify($0, publicKey: publicKey).transaction } == "github:U_1")
170 }
171
119 @Test func storesOnlyKeysThatVerify() throws { 172 @Test func storesOnlyKeysThatVerify() throws {
120 let defaults = try #require(UserDefaults(suiteName: "test.\(UUID().uuidString)")) 173 let defaults = try #require(UserDefaults(suiteName: "test.\(UUID().uuidString)"))
121 #expect(throws: LicenseKey.Failure.malformed) { try LicenseStore.activate("nope", defaults: defaults) } 174 #expect(throws: LicenseKey.Failure.malformed) { try LicenseStore.activate("nope", defaults: defaults) }
l10n/Localizable.xcstrings +173
@@ -4297,6 +4297,7 @@
4297 } 4297 }
4298 }, 4298 },
4299 "Buy orgstar+…": { 4299 "Buy orgstar+…": {
4300 "extractionState": "stale",
4300 "localizations": { 4301 "localizations": {
4301 "de": { 4302 "de": {
4302 "stringUnit": { 4303 "stringUnit": {
@@ -12634,6 +12635,40 @@
12634 } 12635 }
12635 } 12636 }
12636 }, 12637 },
12638 "Get Your Key…": {
12639 "localizations": {
12640 "de": {
12641 "stringUnit": {
12642 "state": "translated",
12643 "value": "Schlüssel abrufen …"
12644 }
12645 },
12646 "es": {
12647 "stringUnit": {
12648 "state": "translated",
12649 "value": "Obtener tu clave…"
12650 }
12651 },
12652 "fr": {
12653 "stringUnit": {
12654 "state": "translated",
12655 "value": "Obtenir votre clé…"
12656 }
12657 },
12658 "ja": {
12659 "stringUnit": {
12660 "state": "translated",
12661 "value": "キーを取得…"
12662 }
12663 },
12664 "pt-BR": {
12665 "stringUnit": {
12666 "state": "translated",
12667 "value": "Obter sua chave…"
12668 }
12669 }
12670 }
12671 },
12637 "Git branch": { 12672 "Git branch": {
12638 "localizations": { 12673 "localizations": {
12639 "de": { 12674 "de": {
@@ -23972,6 +24007,40 @@
23972 } 24007 }
23973 } 24008 }
23974 }, 24009 },
24010 "Renews while you sponsor monthly. This key is valid until %@.": {
24011 "localizations": {
24012 "de": {
24013 "stringUnit": {
24014 "state": "translated",
24015 "value": "Wird verlängert, solange du monatlich sponserst. Dieser Schlüssel gilt bis %@."
24016 }
24017 },
24018 "es": {
24019 "stringUnit": {
24020 "state": "translated",
24021 "value": "Se renueva mientras patrocines cada mes. Esta clave es válida hasta el %@."
24022 }
24023 },
24024 "fr": {
24025 "stringUnit": {
24026 "state": "translated",
24027 "value": "Renouvelée tant que vous sponsorisez chaque mois. Cette clé est valable jusqu'au %@."
24028 }
24029 },
24030 "ja": {
24031 "stringUnit": {
24032 "state": "translated",
24033 "value": "毎月スポンサーを続けている間は更新されます。このキーは%@まで有効です。"
24034 }
24035 },
24036 "pt-BR": {
24037 "stringUnit": {
24038 "state": "translated",
24039 "value": "É renovada enquanto você patrocina mensalmente. Esta chave é válida até %@."
24040 }
24041 }
24042 }
24043 },
23975 "Reparent Note with Descendants…": { 24044 "Reparent Note with Descendants…": {
23976 "comment": "Command title", 24045 "comment": "Command title",
23977 "localizations": { 24046 "localizations": {
@@ -27828,6 +27897,74 @@
27828 } 27897 }
27829 } 27898 }
27830 }, 27899 },
27900 "Sponsor for orgstar+…": {
27901 "localizations": {
27902 "de": {
27903 "stringUnit": {
27904 "state": "translated",
27905 "value": "Für orgstar+ sponsern …"
27906 }
27907 },
27908 "es": {
27909 "stringUnit": {
27910 "state": "translated",
27911 "value": "Patrocinar para orgstar+…"
27912 }
27913 },
27914 "fr": {
27915 "stringUnit": {
27916 "state": "translated",
27917 "value": "Sponsoriser pour orgstar+…"
27918 }
27919 },
27920 "ja": {
27921 "stringUnit": {
27922 "state": "translated",
27923 "value": "スポンサーになってorgstar+を利用…"
27924 }
27925 },
27926 "pt-BR": {
27927 "stringUnit": {
27928 "state": "translated",
27929 "value": "Patrocinar para o orgstar+…"
27930 }
27931 }
27932 }
27933 },
27934 "Sponsors get their key by signing in with GitHub. It is checked on this Mac; a monthly sponsor's key is renewed with krz.sh.": {
27935 "localizations": {
27936 "de": {
27937 "stringUnit": {
27938 "state": "translated",
27939 "value": "Sponsoren erhalten ihren Schlüssel, indem sie sich mit GitHub anmelden. Er wird auf diesem Mac geprüft; der Schlüssel monatlicher Sponsoren wird über krz.sh verlängert."
27940 }
27941 },
27942 "es": {
27943 "stringUnit": {
27944 "state": "translated",
27945 "value": "Los patrocinadores obtienen su clave iniciando sesión con GitHub. Se comprueba en este Mac; la clave de un patrocinador mensual se renueva con krz.sh."
27946 }
27947 },
27948 "fr": {
27949 "stringUnit": {
27950 "state": "translated",
27951 "value": "Les sponsors obtiennent leur clé en se connectant avec GitHub. Elle est vérifiée sur ce Mac ; la clé d'un sponsor mensuel est renouvelée auprès de krz.sh."
27952 }
27953 },
27954 "ja": {
27955 "stringUnit": {
27956 "state": "translated",
27957 "value": "スポンサーはGitHubでサインインしてキーを取得します。キーはこのMac上で確認されます。月額スポンサーのキーはkrz.shで更新されます。"
27958 }
27959 },
27960 "pt-BR": {
27961 "stringUnit": {
27962 "state": "translated",
27963 "value": "Os patrocinadores obtêm a chave entrando com o GitHub. Ela é verificada neste Mac; a chave de um patrocinador mensal é renovada com o krz.sh."
27964 }
27965 }
27966 }
27967 },
27831 "Standard Mac editing keys, with Org commands on ⌃⌘: ⌃⌘T cycles TODO, ⌃⌘S schedules.": { 27968 "Standard Mac editing keys, with Org commands on ⌃⌘: ⌃⌘T cycles TODO, ⌃⌘S schedules.": {
27832 "localizations": { 27969 "localizations": {
27833 "de": { 27970 "de": {
@@ -32570,6 +32707,7 @@
32570 } 32707 }
32571 }, 32708 },
32572 "Your key is in the email from the purchase. It is checked on this Mac; nothing is sent.": { 32709 "Your key is in the email from the purchase. It is checked on this Mac; nothing is sent.": {
32710 "extractionState": "stale",
32573 "localizations": { 32711 "localizations": {
32574 "de": { 32712 "de": {
32575 "stringUnit": { 32713 "stringUnit": {
@@ -34264,7 +34402,42 @@
34264 } 34402 }
34265 } 34403 }
34266 }, 34404 },
34405 "orgstar+ for Mac comes with sponsoring orgstar on GitHub: $60 once, or $5 a month. Editing, the agenda, capture, clocking and search stay free.": {
34406 "localizations": {
34407 "de": {
34408 "stringUnit": {
34409 "state": "translated",
34410 "value": "orgstar+ für Mac gibt es, wenn du orgstar auf GitHub sponserst: einmalig $60 oder $5 im Monat. Bearbeiten, Agenda, Erfassen, Zeiterfassung und Suche bleiben kostenlos."
34411 }
34412 },
34413 "es": {
34414 "stringUnit": {
34415 "state": "translated",
34416 "value": "orgstar+ para Mac se incluye al patrocinar orgstar en GitHub: $60 una vez o $5 al mes. La edición, la agenda, la captura, el registro de tiempo y la búsqueda siguen siendo gratuitos."
34417 }
34418 },
34419 "fr": {
34420 "stringUnit": {
34421 "state": "translated",
34422 "value": "orgstar+ pour Mac est inclus quand vous sponsorisez orgstar sur GitHub : $60 une fois, ou $5 par mois. L'édition, l'agenda, la capture, le chronométrage et la recherche restent gratuits."
34423 }
34424 },
34425 "ja": {
34426 "stringUnit": {
34427 "state": "translated",
34428 "value": "Mac版orgstar+は、GitHubでorgstarのスポンサーになると利用できます(1回$60、または月額$5)。編集、アジェンダ、キャプチャ、クロック、検索は引き続き無料です。"
34429 }
34430 },
34431 "pt-BR": {
34432 "stringUnit": {
34433 "state": "translated",
34434 "value": "O orgstar+ para Mac vem com o patrocínio do orgstar no GitHub: $60 uma vez ou $5 por mês. A edição, a agenda, a captura, o registro de tempo e a busca continuam gratuitos."
34435 }
34436 }
34437 }
34438 },
34267 "orgstar+ is a one-time purchase of $39.99 for this Mac. Editing, the agenda, capture, clocking and search stay free.": { 34439 "orgstar+ is a one-time purchase of $39.99 for this Mac. Editing, the agenda, capture, clocking and search stay free.": {
34440 "extractionState": "stale",
34268 "localizations": { 34441 "localizations": {
34269 "de": { 34442 "de": {
34270 "stringUnit": { 34443 "stringUnit": {
packaging/license-issuer/.dev.vars.example +8 −6
@@ -1,8 +1,10 @@
1# Secrets for `npx wrangler dev --env sandbox`: copy to .dev.vars (ignored by git) and fill in. 1# Secrets for `npx wrangler dev`: copy to .dev.vars (ignored by git) and fill in.
2# Deployed Workers take them from `npx wrangler secret put NAME [--env sandbox]` instead. 2# Deployed Workers take them from `npx wrangler secret put NAME` instead.
3# Client-side token: test_… (sandbox) or live_…, from Paddle > Developer tools > Authentication. 3# The GitHub OAuth app's client secret. For local runs, use a second OAuth app whose callback
4PADDLE_CLIENT_TOKEN=test_ 4# URL is http://localhost:8787/license, and override GITHUB_CLIENT_ID here.
5# API key with transaction.read and customer.read: pdl_sdbx_apikey_… (sandbox) or pdl_live_apikey_…. 5GITHUB_CLIENT_SECRET=
6PADDLE_API_KEY= 6# A token of the SPONSORABLE account with read:user, for renewals (classic token, or
7# fine-grained with no repository access).
8GITHUB_TOKEN=
7# PKCS#8 PEM from keygen.sh, on one line with \n for line breaks. 9# PKCS#8 PEM from keygen.sh, on one line with \n for line breaks.
8LICENSE_PRIVATE_KEY= 10LICENSE_PRIVATE_KEY=
packaging/license-issuer/worker.js +217 −109
@@ -1,153 +1,261 @@
1// Serves the orgstar+ for Mac buy page and issues license keys for completed Paddle transactions. 1// Issues orgstar+ for Mac license keys to GitHub sponsors. Paths are matched by their last
2// Both paths are matched by their last segment, so the Worker answers under any route: 2// segment, so the Worker answers under any route: krz.sh/apps/orgstar/buy, or /buy under
3// krz.sh/apps/orgstar/buy, krz.sh/apps/orgstar/sandbox/buy, or /buy under `wrangler dev`. 3// `wrangler dev`.
4// 4//
5// GET …/buy shows the price from Paddle.PricePreview, localized to the visitor's country (from 5// GET …/buy shows what orgstar+ includes and the two sponsorships that come with a key, linking to
6// Cloudflare's request.cf, omitted when unknown so Paddle.js detects it from the IP), and opens 6// github.com/sponsors/SPONSORABLE, and to …/license for a sponsor's key.
7// Paddle Checkout as a one-page overlay. On checkout.completed it goes to …/license?txn=txn_….
8// 7//
9// GET …/license?txn=txn_… looks the transaction up in Paddle, and when it is completed and 8// GET …/license signs in with GitHub (OAuth, state in a cookie) and asks GitHub for the visitor's
10// includes PRICE_ID, returns `ORGSTAR1-<payload>.<signature>`: base64url JSON 9// sponsorship of SPONSORABLE:
11// {"e": email, "t": transaction, "i": billed-at seconds}, signed with Ed25519. The app checks the 10// - one-time, LIFETIME_DOLLARS or more: a key that doesn't expire, the same one each time;
12// signature offline (Sources/OrgApp/LicenseKey.swift). Ed25519 signatures are deterministic, so the 11// - monthly and active, MONTHLY_DOLLARS or more: a key that expires RENEW_DAYS after it is issued.
13// same transaction always yields the same key; nothing is stored.
14// 12//
15// Vars (wrangler.toml, per environment): PADDLE_ENV ("sandbox" or "production", no default), PRICE_ID. 13// POST …/renew with a monthly key as the body returns a fresh one while that sponsorship is
16// Secrets (`wrangler secret put NAME [--env sandbox]`; locally .dev.vars, see .dev.vars.example): 14// still active (403 when it isn't). orgstar renews monthly keys in the background.
17// PADDLE_CLIENT_TOKEN (test_… or live_…), PADDLE_API_KEY, LICENSE_PRIVATE_KEY (PKCS#8 PEM, from 15//
18// keygen.sh; the sandbox Worker takes the same key). 16// A key is `ORGSTAR1-<payload>.<signature>`: base64url JSON {"e": GitHub login, "t": "github:" +
19 17// the account's node ID, "i": issued, "x": expires (monthly keys only), seconds}, signed with
20// The buy page's copy. The price comes from Paddle. 18// Ed25519. The app checks it offline (Sources/OrgApp/LicenseKey.swift). Nothing is stored.
21const PRODUCT = { 19//
22 name: "orgstar+ for Mac", 20// Vars (wrangler.toml): SPONSORABLE, LIFETIME_DOLLARS, MONTHLY_DOLLARS, RENEW_DAYS,
23 description: "One payment, a license key that doesn't expire. Editing, the agenda, capture, clocking, tables and search stay free.", 21// GITHUB_CLIENT_ID. Secrets (`wrangler secret put NAME`; locally .dev.vars, see
24 features: [ 22// .dev.vars.example): GITHUB_CLIENT_SECRET, GITHUB_TOKEN (SPONSORABLE's token, for renewals),
25 "Run and tangle source blocks", 23// LICENSE_PRIVATE_KEY (PKCS#8 PEM, from keygen.sh).
26 "PDF, Word and other export, and publishing",
27 "Encrypted entries",
28 "Org-roam nodes and backlinks",
29 "Widgets",
30 "Calendar and Reminders",
31 "Shortcuts actions",
32 ],
33};
34 24
35const PADDLE_API = { sandbox: "https://sandbox-api.paddle.com", production: "https://api.paddle.com" }; 25const FEATURES = [
26 "Run and tangle source blocks",
27 "PDF, Word and other export, and publishing",
28 "Encrypted entries",
29 "Org-roam and Denote notes, daily notes and backlinks",
30 "Widgets",
31 "Calendar and Reminders",
32 "Shortcuts actions",
33];
36 34
37/// Reads the settings a path needs and throws when one is missing or belongs to the other environment. 35const STATE_COOKIE = "orgstar_state";
38function settings(env, ...needs) { 36
39 const api = PADDLE_API[env.PADDLE_ENV]; 37/// Reads the settings and throws when one is missing.
40 if (!api) throw new Error(`PADDLE_ENV must be "sandbox" or "production", not ${JSON.stringify(env.PADDLE_ENV)}`); 38function settings(env, ...secrets) {
41 if (!/^pri_[a-z\d]{26}$/.test(env.PRICE_ID ?? "")) throw new Error(`PRICE_ID isn't a Paddle price ID: ${JSON.stringify(env.PRICE_ID)}`); 39 for (const name of ["SPONSORABLE", ...secrets])
42 const prefix = env.PADDLE_ENV === "sandbox" ? "test_" : "live_"; 40 if (!env[name]) throw new Error(`${name} is not set`);
43 if (needs.includes("token") && !env.PADDLE_CLIENT_TOKEN?.startsWith(prefix)) 41 const number = (name) => {
44 throw new Error(`PADDLE_CLIENT_TOKEN must be a ${prefix}… client-side token for ${env.PADDLE_ENV}`); 42 const value = Number(env[name]);
45 for (const name of ["PADDLE_API_KEY", "LICENSE_PRIVATE_KEY"]) 43 if (!(value > 0)) throw new Error(`${name} must be a positive number, not ${JSON.stringify(env[name])}`);
46 if (needs.includes("issuer") && !env[name]) throw new Error(`${name} is not set`); 44 return value;
47 return { api, sandbox: env.PADDLE_ENV === "sandbox" }; 45 };
46 return {
47 sponsorable: env.SPONSORABLE,
48 lifetime: number("LIFETIME_DOLLARS"),
49 monthly: number("MONTHLY_DOLLARS"),
50 renewDays: number("RENEW_DAYS"),
51 };
48} 52}
49 53
50export default { 54export default {
51 async fetch(request, env) { 55 async fetch(request, env) {
52 const url = new URL(request.url); 56 const url = new URL(request.url);
53 if (url.pathname.endsWith("/buy")) return buy(request, env); 57 if (url.pathname.endsWith("/buy")) return buy(url, env);
54 if (url.pathname.endsWith("/license")) return license(url, env); 58 if (url.pathname.endsWith("/license")) return license(request, url, env);
59 if (url.pathname.endsWith("/renew") && request.method === "POST") return renew(request, env);
55 return new Response("Not found", { status: 404 }); 60 return new Response("Not found", { status: 404 });
56 }, 61 },
57}; 62};
58 63
59function buy(request, env) { 64function buy(url, env) {
60 const { sandbox } = settings(env, "token"); 65 const { sponsorable, lifetime, monthly } = settings(env);
61 const country = request.cf?.country; 66 const features = FEATURES.map((feature) => `<li>${feature}</li>`).join("");
62 const config = {
63 sandbox,
64 token: env.PADDLE_CLIENT_TOKEN,
65 priceId: env.PRICE_ID,
66 // XX is Cloudflare's unknown and T1 is Tor; Paddle.js detects the country itself without one.
67 country: /^[A-Z]{2}$/.test(country ?? "") && country !== "XX" && country !== "T1" ? country : null,
68 };
69 const features = PRODUCT.features.map((feature) => `<li>${feature}</li>`).join("");
70 return page( 67 return page(
71 `<p>${PRODUCT.description}</p><ul>${features}</ul>` + 68 `<p>orgstar+ for Mac comes with sponsoring orgstar on GitHub. Editing, the agenda, capture, ` +
72 `<p class="price" id="price">Loading the price…</p>` + 69 `clocking, tables and search stay free.</p><ul>${features}</ul>` +
73 `<button id="buy" type="button">Buy ${PRODUCT.name}</button>` + 70 `<ul class="tiers"><li><b>$${lifetime} once</b>: a license key that doesn't expire.</li>` +
74 `<p class="note">Checkout is by Paddle, the merchant of record. Your key shows on the next page.</p>` + 71 `<li><b>$${monthly} a month</b>: a key that orgstar renews while you sponsor.</li></ul>` +
75 `<script src="https://cdn.paddle.com/paddle/v2/paddle.js"></script>` + 72 `<p><a class="button" href="https://github.com/sponsors/${sponsorable}">Sponsor on GitHub</a></p>` +
76 `<script>const config = ${JSON.stringify(config).replace(/</g, "\\u003c")};\n${BUY_SCRIPT}</script>`, 73 `<p>Then <a href="${new URL("license", url)}">sign in with GitHub to get your key</a>.</p>` +
74 `<p class="note">Payment is through GitHub Sponsors and needs a GitHub account.</p>`,
77 200, 75 200,
78 PRODUCT.name, 76 "orgstar+ for Mac",
79 ); 77 );
80} 78}
81 79
82// Runs on the buy page. Shows only Paddle's formatted total; does no price arithmetic. 80async function license(request, url, env) {
83const BUY_SCRIPT = ` 81 const config = settings(env, "GITHUB_CLIENT_ID", "GITHUB_CLIENT_SECRET", "LICENSE_PRIVATE_KEY");
84if (config.sandbox) Paddle.Environment.set("sandbox"); 82 const self = new URL(url.pathname, url);
85Paddle.Initialize({ 83 const code = url.searchParams.get("code");
86 token: config.token, 84 if (!code) {
87 eventCallback(event) { 85 const state = [...crypto.getRandomValues(new Uint8Array(16))].map((b) => b.toString(16).padStart(2, "0")).join("");
88 if (event.name === "checkout.completed") 86 const authorize = new URL("https://github.com/login/oauth/authorize");
89 location.href = new URL("license?txn=" + encodeURIComponent(event.data.transaction_id), location.href); 87 authorize.searchParams.set("client_id", env.GITHUB_CLIENT_ID);
90 }, 88 authorize.searchParams.set("redirect_uri", self.href);
91}); 89 authorize.searchParams.set("scope", "read:user");
92const items = [{ priceId: config.priceId, quantity: 1 }]; 90 authorize.searchParams.set("state", state);
93const request = config.country ? { items, address: { countryCode: config.country } } : { items }; 91 authorize.searchParams.set("allow_signup", "true");
94Paddle.PricePreview(request) 92 return new Response(null, {
95 .then((preview) => { 93 status: 302,
96 document.getElementById("price").textContent = preview.data.details.lineItems[0].formattedTotals.total; 94 headers: {
97 }) 95 location: authorize.href,
98 .catch(() => { 96 "set-cookie": `${STATE_COOKIE}=${state}; Path=${url.pathname}; Max-Age=600; HttpOnly; Secure; SameSite=Lax`,
99 document.getElementById("price").textContent = "The price shows at checkout."; 97 },
100 }); 98 });
101document.getElementById("buy").onclick = () => 99 }
102 Paddle.Checkout.open({ items, settings: { displayMode: "overlay", variant: "one-page" } });
103`;
104 100
105async function license(url, env) { 101 const cookie = (request.headers.get("cookie") ?? "").split(/;\s*/).find((c) => c.startsWith(STATE_COOKIE + "="));
106 const { api } = settings(env, "issuer"); 102 if (!cookie || cookie.slice(STATE_COOKIE.length + 1) !== url.searchParams.get("state"))
107 const txn = url.searchParams.get("txn") ?? ""; 103 return page(`The sign-in expired. <a href="${self}">Sign in again</a>.`, 400);
108 if (!/^txn_[a-z0-9]{20,40}$/.test(txn)) return page("That isn't a Paddle transaction ID.", 400);
109 104
110 const response = await fetch(`${api}/transactions/${txn}?include=customer`, { 105 const exchange = await fetch("https://github.com/login/oauth/access_token", {
111 headers: { Authorization: `Bearer ${env.PADDLE_API_KEY}` }, 106 method: "POST",
107 headers: { accept: "application/json", "content-type": "application/json" },
108 body: JSON.stringify({ client_id: env.GITHUB_CLIENT_ID, client_secret: env.GITHUB_CLIENT_SECRET, code, redirect_uri: self.href }),
112 }); 109 });
113 if (response.status === 404) return page("No purchase was found for that transaction.", 404); 110 const token = exchange.ok ? (await exchange.json()).access_token : null;
114 if (!response.ok) return page("Paddle can't be reached right now. Try again in a minute.", 502); 111 if (!token) return page(`GitHub didn't complete the sign-in. <a href="${self}">Try again</a>.`, 502);
115 const { data } = await response.json(); 112
116 const paid = data.status === "completed" || data.status === "paid"; 113 const data = await graphql(
117 const forOrgstar = data.items?.some((item) => item.price?.id === env.PRICE_ID); 114 token,
118 if (!paid || !forOrgstar) return page("That transaction isn't a completed orgstar+ purchase.", 404); 115 `query($login: String!) {
119 116 viewer { id login }
120 const key = await sign( 117 user(login: $login) {
121 { e: data.customer?.email ?? "", t: txn, i: Math.floor(Date.parse(data.billed_at ?? data.created_at) / 1000) }, 118 sponsorshipForViewerAsSponsor(activeOnly: false) {
122 env.LICENSE_PRIVATE_KEY, 119 isActive createdAt tier { monthlyPriceInDollars isOneTime }
120 }
121 }
122 }`,
123 { login: config.sponsorable },
123 ); 124 );
124 if (url.searchParams.get("format") === "text") return new Response(key + "\n"); 125 if (!data) return page("GitHub can't be reached right now. Try again in a minute.", 502);
126
127 const { viewer } = data;
128 const kind = entitlement(data.user?.sponsorshipForViewerAsSponsor, config);
129 const sponsor = `https://github.com/sponsors/${config.sponsorable}`;
130 const clear = { "set-cookie": `${STATE_COOKIE}=; Path=${url.pathname}; Max-Age=0; HttpOnly; Secure; SameSite=Lax` };
131 if (!kind)
132 return page(
133 `${escape(viewer.login)} isn't sponsoring at a level that includes orgstar+: $${config.lifetime} once, ` +
134 `or $${config.monthly} or more a month. <a href="${sponsor}">Sponsor on GitHub</a>, then come back to this page.`,
135 403,
136 "orgstar+",
137 clear,
138 );
139
140 const t = "github:" + viewer.id;
141 const payload = kind === "lifetime"
142 ? { e: viewer.login, t, i: seconds(data.user.sponsorshipForViewerAsSponsor.createdAt) }
143 : monthlyPayload(viewer.login, t, config.renewDays);
144 const key = await sign(payload, env.LICENSE_PRIVATE_KEY);
145 const note = kind === "lifetime"
146 ? "It doesn't expire, and this page shows the same key whenever you sign in again."
147 : `orgstar renews it while your monthly sponsorship continues. If you stop, orgstar+ ends when the key expires.`;
125 return page( 148 return page(
126 `<p>Your orgstar+ license key:</p><pre>${key}</pre>` + 149 `<p>Your orgstar+ license key:</p><pre>${key}</pre>` +
127 `<p>In orgstar, open Settings ▸ orgstar+, paste the key and choose Activate. Keep this page or the key; ` + 150 `<p>In orgstar, open Settings ▸ orgstar+, paste the key and choose Activate. ${note}</p>`,
128 `the same link shows it again.</p>`,
129 200, 151 200,
152 "orgstar+",
153 clear,
130 ); 154 );
131} 155}
132 156
157/// "lifetime", "monthly" or null for a sponsorship from GitHub's API.
158export function entitlement(sponsorship, { lifetime, monthly }) {
159 const dollars = sponsorship?.tier?.monthlyPriceInDollars ?? 0;
160 if (!sponsorship) return null;
161 if (sponsorship.tier?.isOneTime) return dollars >= lifetime ? "lifetime" : null;
162 return sponsorship.isActive && dollars >= monthly ? "monthly" : null;
163}
164
165function monthlyPayload(login, t, renewDays) {
166 const now = Math.floor(Date.now() / 1000);
167 return { e: login, t, i: now, x: now + renewDays * 86400 };
168}
169
170async function renew(request, env) {
171 const config = settings(env, "GITHUB_TOKEN", "LICENSE_PRIVATE_KEY");
172 const payload = await verify((await request.text()).replace(/\s/g, ""), env.LICENSE_PRIVATE_KEY);
173 if (!payload?.x || !payload.t?.startsWith("github:")) return text("Not a monthly orgstar+ key.", 400);
174
175 const data = await graphql(
176 env.GITHUB_TOKEN,
177 `query($id: ID!) {
178 node(id: $id) {
179 ... on User { login sponsorshipForViewerAsSponsorable(activeOnly: true) { isActive tier { monthlyPriceInDollars isOneTime } } }
180 ... on Organization { login sponsorshipForViewerAsSponsorable(activeOnly: true) { isActive tier { monthlyPriceInDollars isOneTime } } }
181 }
182 }`,
183 { id: payload.t.slice("github:".length) },
184 );
185 if (!data) return text("GitHub can't be reached right now.", 502);
186 const node = data.node;
187 if (entitlement(node?.sponsorshipForViewerAsSponsorable, config) !== "monthly")
188 return text("The monthly sponsorship has ended.", 403);
189 return text(await sign(monthlyPayload(node.login, payload.t, config.renewDays), env.LICENSE_PRIVATE_KEY), 200);
190}
191
192async function graphql(token, query, variables) {
193 const response = await fetch("https://api.github.com/graphql", {
194 method: "POST",
195 headers: { authorization: `Bearer ${token}`, "content-type": "application/json", "user-agent": "orgstar-license" },
196 body: JSON.stringify({ query, variables }),
197 });
198 if (!response.ok) return null;
199 const body = await response.json();
200 return body.data ?? null;
201}
202
203function seconds(iso) {
204 return Math.floor(Date.parse(iso) / 1000);
205}
206
207async function keys(pem) {
208 const der = Uint8Array.from(atob(pem.replace(/-----[^-]+-----|\s|\\n/g, "")), (c) => c.charCodeAt(0));
209 const privateKey = await crypto.subtle.importKey("pkcs8", der, { name: "Ed25519" }, true, ["sign"]);
210 const { x } = await crypto.subtle.exportKey("jwk", privateKey);
211 const publicKey = await crypto.subtle.importKey("jwk", { kty: "OKP", crv: "Ed25519", x }, { name: "Ed25519" }, false, ["verify"]);
212 return { privateKey, publicKey };
213}
214
133export async function sign(payload, pem) { 215export async function sign(payload, pem) {
134 const der = Uint8Array.from(atob(pem.replace(/-----[^-]+-----|\s/g, "")), (c) => c.charCodeAt(0)); 216 const { privateKey } = await keys(pem);
135 const privateKey = await crypto.subtle.importKey("pkcs8", der, { name: "Ed25519" }, false, ["sign"]);
136 const body = new TextEncoder().encode(JSON.stringify(payload)); 217 const body = new TextEncoder().encode(JSON.stringify(payload));
137 const signature = new Uint8Array(await crypto.subtle.sign({ name: "Ed25519" }, privateKey, body)); 218 const signature = new Uint8Array(await crypto.subtle.sign({ name: "Ed25519" }, privateKey, body));
138 return `ORGSTAR1-${base64url(body)}.${base64url(signature)}`; 219 return `ORGSTAR1-${base64url(body)}.${base64url(signature)}`;
139} 220}
140 221
222/// The payload of a key this issuer signed, or null.
223export async function verify(key, pem) {
224 const match = /^ORGSTAR1-([\w-]+)\.([\w-]+)$/.exec(key);
225 if (!match) return null;
226 const [body, signature] = [unbase64url(match[1]), unbase64url(match[2])];
227 const { publicKey } = await keys(pem);
228 if (!(await crypto.subtle.verify({ name: "Ed25519" }, publicKey, signature, body))) return null;
229 try {
230 return JSON.parse(new TextDecoder().decode(body));
231 } catch {
232 return null;
233 }
234}
235
141function base64url(bytes) { 236function base64url(bytes) {
142 return btoa(String.fromCharCode(...bytes)).replace(/\+/g, "-").replace(/\//g, "_").replace(/=+$/, ""); 237 return btoa(String.fromCharCode(...bytes)).replace(/\+/g, "-").replace(/\//g, "_").replace(/=+$/, "");
143} 238}
144 239
145function page(body, status, heading = "orgstar+") { 240function unbase64url(text) {
241 const padded = text.replace(/-/g, "+").replace(/_/g, "/") + "=".repeat((4 - (text.length % 4)) % 4);
242 return Uint8Array.from(atob(padded), (c) => c.charCodeAt(0));
243}
244
245function escape(text) {
246 return String(text).replace(/[&<>"]/g, (c) => ({ "&": "&amp;", "<": "&lt;", ">": "&gt;", '"': "&quot;" })[c]);
247}
248
249function text(body, status) {
250 return new Response(body + "\n", { status, headers: { "content-type": "text/plain; charset=utf-8" } });
251}
252
253function page(body, status, heading = "orgstar+", headers = {}) {
146 const html = `<!doctype html><meta charset="utf-8"><meta name="viewport" content="width=device-width">` + 254 const html = `<!doctype html><meta charset="utf-8"><meta name="viewport" content="width=device-width">` +
147 `<title>${heading}</title><style>body{font:16px/1.5 system-ui;max-width:40rem;margin:3rem auto;padding:0 1rem}` + 255 `<title>${heading}</title><style>body{font:16px/1.5 system-ui;max-width:40rem;margin:3rem auto;padding:0 1rem}` +
148 `pre{white-space:pre-wrap;word-break:break-all;background:#f4f4f4;padding:1rem;border-radius:6px}` + 256 `pre{white-space:pre-wrap;word-break:break-all;background:#f4f4f4;padding:1rem;border-radius:6px}` +
149 `.price{font-size:1.75rem;font-weight:600;margin:1.5rem 0 .75rem}.note{color:#666;font-size:.9rem}` + 257 `.tiers{list-style:none;padding:0}.note{color:#666;font-size:.9rem}` +
150 `button{font:inherit;font-weight:600;padding:.7rem 1.4rem;border:0;border-radius:8px;background:#d4a017;color:#fff;cursor:pointer}</style>` + 258 `.button{display:inline-block;font-weight:600;padding:.7rem 1.4rem;border-radius:8px;background:#d4a017;color:#fff;text-decoration:none}</style>` +
151 `<h1>${heading}</h1>${body.startsWith("<") ? body : `<p>${body}</p>`}`; 259 `<h1>${heading}</h1>${body.startsWith("<") ? body : `<p>${body}</p>`}`;
152 return new Response(html, { status, headers: { "content-type": "text/html; charset=utf-8" } }); 260 return new Response(html, { status, headers: { "content-type": "text/html; charset=utf-8", ...headers } });
153} 261}
packaging/license-issuer/worker.test.mjs added +131
@@ -0,0 +1,131 @@
1// node --test packaging/license-issuer
2import assert from "node:assert/strict";
3import { generateKeyPairSync } from "node:crypto";
4import { test } from "node:test";
5import worker, { entitlement, sign, verify } from "./worker.js";
6
7const pem = generateKeyPairSync("ed25519").privateKey.export({ type: "pkcs8", format: "pem" });
8const env = {
9 SPONSORABLE: "maintainer",
10 LIFETIME_DOLLARS: "60",
11 MONTHLY_DOLLARS: "5",
12 RENEW_DAYS: "40",
13 GITHUB_CLIENT_ID: "client",
14 GITHUB_CLIENT_SECRET: "secret",
15 GITHUB_TOKEN: "maintainer-token",
16 LICENSE_PRIVATE_KEY: pem,
17};
18const config = { lifetime: 60, monthly: 5 };
19
20/// Replaces fetch with `respond(url, init)` for the length of `body`.
21async function withFetch(respond, body) {
22 const original = globalThis.fetch;
23 globalThis.fetch = async (url, init) => respond(String(url), init);
24 try {
25 return await body();
26 } finally {
27 globalThis.fetch = original;
28 }
29}
30
31const json = (data) => new Response(JSON.stringify(data), { headers: { "content-type": "application/json" } });
32const sponsorship = (dollars, { oneTime = false, active = true } = {}) => ({
33 isActive: active,
34 createdAt: "2026-11-01T12:00:00Z",
35 tier: { monthlyPriceInDollars: dollars, isOneTime: oneTime },
36});
37
38test("keys verify and tampered keys don't", async () => {
39 const key = await sign({ e: "octo", t: "github:U_1", i: 1 }, pem);
40 assert.deepEqual(await verify(key, pem), { e: "octo", t: "github:U_1", i: 1 });
41 const other = generateKeyPairSync("ed25519").privateKey.export({ type: "pkcs8", format: "pem" });
42 assert.equal(await verify(await sign({ e: "octo", t: "github:U_1", i: 1 }, other), pem), null);
43 assert.equal(await verify("ORGSTAR1-abc", pem), null);
44});
45
46test("one-time $60 is lifetime, active monthly $5 is monthly, anything else is nothing", () => {
47 assert.equal(entitlement(sponsorship(60, { oneTime: true, active: false }), config), "lifetime");
48 assert.equal(entitlement(sponsorship(100, { oneTime: true }), config), "lifetime");
49 assert.equal(entitlement(sponsorship(40, { oneTime: true }), config), null);
50 assert.equal(entitlement(sponsorship(5), config), "monthly");
51 assert.equal(entitlement(sponsorship(5, { active: false }), config), null);
52 assert.equal(entitlement(sponsorship(2), config), null);
53 assert.equal(entitlement(null, config), null);
54});
55
56test("/license without a code redirects to GitHub with a state cookie", async () => {
57 const response = await worker.fetch(new Request("https://krz.sh/apps/orgstar/license"), env);
58 assert.equal(response.status, 302);
59 const location = new URL(response.headers.get("location"));
60 assert.equal(location.origin + location.pathname, "https://github.com/login/oauth/authorize");
61 assert.equal(location.searchParams.get("redirect_uri"), "https://krz.sh/apps/orgstar/license");
62 assert.match(response.headers.get("set-cookie"), new RegExp(`orgstar_state=${location.searchParams.get("state")};`));
63});
64
65/// The callback, with GitHub answering `sponsor` for the signed-in visitor.
66async function callback(sponsor, { state = "abc", cookie = "abc" } = {}) {
67 return withFetch(
68 (url) => url.includes("access_token")
69 ? json({ access_token: "visitor-token" })
70 : json({ data: { viewer: { id: "U_1", login: "octo" }, user: { sponsorshipForViewerAsSponsor: sponsor } } }),
71 () => worker.fetch(
72 new Request(`https://krz.sh/apps/orgstar/license?code=c&state=${state}`, { headers: { cookie: `orgstar_state=${cookie}` } }),
73 env,
74 ),
75 );
76}
77
78const keyIn = async (response) => /<pre>([^<]+)<\/pre>/.exec(await response.text())?.[1];
79
80test("a one-time sponsor gets the same lifetime key each time", async () => {
81 const first = await keyIn(await callback(sponsorship(60, { oneTime: true, active: false })));
82 const second = await keyIn(await callback(sponsorship(60, { oneTime: true, active: false })));
83 assert.equal(first, second);
84 assert.deepEqual(await verify(first, pem), { e: "octo", t: "github:U_1", i: Date.parse("2026-11-01T12:00:00Z") / 1000 });
85});
86
87test("a monthly sponsor gets a key that expires", async () => {
88 const payload = await verify(await keyIn(await callback(sponsorship(5))), pem);
89 assert.equal(payload.x - payload.i, 40 * 86400);
90});
91
92test("a visitor who isn't sponsoring enough gets no key", async () => {
93 const response = await callback(sponsorship(1));
94 assert.equal(response.status, 403);
95 assert.equal(await keyIn(response), undefined);
96});
97
98test("a callback whose state doesn't match the cookie is refused", async () => {
99 assert.equal((await callback(sponsorship(5), { cookie: "other" })).status, 400);
100});
101
102/// …/renew with `key`, GitHub answering `sponsor` for the key's account.
103async function renewal(key, sponsor) {
104 let asked;
105 const response = await withFetch(
106 (url, init) => {
107 asked = JSON.parse(init.body).variables;
108 return json({ data: { node: { login: "octo-renamed", sponsorshipForViewerAsSponsorable: sponsor } } });
109 },
110 () => worker.fetch(new Request("https://krz.sh/apps/orgstar/renew", { method: "POST", body: key }), env),
111 );
112 return { response, asked };
113}
114
115test("renewal extends a monthly key while the sponsorship is active", async () => {
116 const old = await sign({ e: "octo", t: "github:U_1", i: 1, x: 2 }, pem);
117 const { response, asked } = await renewal(old, sponsorship(5));
118 assert.equal(response.status, 200);
119 assert.deepEqual(asked, { id: "U_1" });
120 const fresh = await verify((await response.text()).trim(), pem);
121 assert.equal(fresh.e, "octo-renamed");
122 assert.ok(fresh.x > Date.now() / 1000 + 39 * 86400);
123});
124
125test("renewal refuses ended sponsorships, lifetime keys and forged keys", async () => {
126 const monthly = await sign({ e: "octo", t: "github:U_1", i: 1, x: 2 }, pem);
127 assert.equal((await renewal(monthly, null)).response.status, 403);
128 assert.equal((await renewal(await sign({ e: "octo", t: "github:U_1", i: 1 }, pem), sponsorship(5))).response.status, 400);
129 const other = generateKeyPairSync("ed25519").privateKey.export({ type: "pkcs8", format: "pem" });
130 assert.equal((await renewal(await sign({ e: "octo", t: "github:U_1", i: 1, x: 2 }, other), sponsorship(5))).response.status, 400);
131});
packaging/license-issuer/wrangler.toml +8 −14
@@ -1,23 +1,17 @@
1name = "orgstar-license" 1name = "orgstar-license"
2main = "worker.js" 2main = "worker.js"
3compatibility_date = "2026-10-01" 3compatibility_date = "2026-10-01"
4# Paddle approves krz.sh as the live checkout domain.
5routes = [ 4routes = [
6 { pattern = "krz.sh/apps/orgstar/buy*", zone_name = "krz.sh" }, 5 { pattern = "krz.sh/apps/orgstar/buy*", zone_name = "krz.sh" },
7 { pattern = "krz.sh/apps/orgstar/license*", zone_name = "krz.sh" }, 6 { pattern = "krz.sh/apps/orgstar/license*", zone_name = "krz.sh" },
7 { pattern = "krz.sh/apps/orgstar/renew*", zone_name = "krz.sh" },
8] 8]
9 9
10[vars] 10[vars]
11PADDLE_ENV = "production" 11SPONSORABLE = "ccleberg"
12# The orgstar+ for Mac price in the live account, pri_… 12LIFETIME_DOLLARS = "60"
13PRICE_ID = "pri_01m7c397a7ty57r349ye22exta" 13MONTHLY_DOLLARS = "5"
14 14# A monthly key lasts this long; the app renews it well before.
15# npx wrangler deploy --env sandbox. The sandbox account's default payment link is 15RENEW_DAYS = "40"
16# https://krz.sh/apps/orgstar/sandbox/buy. 16# The GitHub OAuth app's client ID. Its callback URL is https://krz.sh/apps/orgstar/license.
17[env.sandbox] 17GITHUB_CLIENT_ID = ""
18name = "orgstar-license-sandbox"
19routes = [{ pattern = "krz.sh/apps/orgstar/sandbox/*", zone_name = "krz.sh" }]
20
21[env.sandbox.vars]
22PADDLE_ENV = "sandbox"
23PRICE_ID = "pri_01m7c13kgj4jcb8xek3ej93j8c"