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
6767Submit new in-app purchases with an app version. Changes take up to an hour to reach the
6868sandbox; test there with a Sandbox Apple Account (Settings ▸ Developer on the device).
6969
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
7090* Tests
7191
7292#+BEGIN_SRC sh
README.org +3 −2
@@ -67,8 +67,9 @@ backlinks; widgets, the Apple Watch app and the clock Live Activity; Calendar an
6767the agenda; and Shortcuts actions.
6868
6969- 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
71 Settings ▸ orgstar+.
70- Mac: by [[https://github.com/sponsors/ccleberg][sponsoring on GitHub]], $60 once for a license key that doesn't expire,
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+.
7273
7374Anyone who installed orgstar before orgstar+ keeps every feature without buying it.
7475
Sources/OrgApp/LicenseKey.swift +54 −13
@@ -2,21 +2,24 @@ import CryptoKit
22import Foundation
33
44/// 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`.
67public struct LicenseKey: Codable, Sendable, Equatable {
7 /// The email the license was sold to.
8 public let email: String
9 /// The payment provider's transaction ID.
8 /// Who the license is for: the sponsor's GitHub login.
9 public let holder: String
10 /// The sponsoring account, `github:<node ID>`.
1011 public let transaction: String
1112 /// When the key was issued, as Unix seconds.
1213 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?
1316
1417 enum CodingKeys: String, CodingKey {
15 case email = "e", transaction = "t", issued = "i"
18 case holder = "e", transaction = "t", issued = "i", expires = "x"
1619 }
1720
1821 public enum Failure: Error, Equatable {
19 case malformed, badSignature
22 case malformed, badSignature, expired
2023 }
2124
2225 static let prefix = "ORGSTAR1-"
@@ -26,10 +29,15 @@ public struct LicenseKey: Codable, Sendable, Equatable {
2629 /// `scripts/release-mac.sh` refuses to build.
2730 public static let publicKey = "bsxWsmNYsFJiN6e/UaBgRzAmHBry9+sjI8BFFbf21aM="
2831
29 public init(email: String, transaction: String, issued: Int) {
30 self.email = email
32 public init(holder: String, transaction: String, issued: Int, expires: Int? = nil) {
33 self.holder = holder
3134 self.transaction = transaction
3235 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
3341 }
3442
3543 /// Checks `text` (whitespace and line breaks from pasting are ignored) and returns the license.
@@ -52,15 +60,48 @@ public struct LicenseKey: Codable, Sendable, Equatable {
5260/// The Mac app's stored license.
5361public enum LicenseStore {
5462 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 }
5577
56 /// The stored key's license, if it still verifies.
57 public static func current(defaults: UserDefaults = .standard) -> LicenseKey? {
58 defaults.string(forKey: key).flatMap { try? LicenseKey.verify($0) }
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
5997 }
6098
6199 /// Verifies and stores `text`.
62 public static func activate(_ text: String, defaults: UserDefaults = .standard) throws(LicenseKey.Failure) -> LicenseKey {
63 let license = try LicenseKey.verify(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 }
64105 defaults.set(text.filter { !$0.isWhitespace }, forKey: key)
65106 return license
66107 }
Sources/Orgstar/OrgstarApp.swift +1
@@ -325,6 +325,7 @@ struct OrgstarApp: App {
325325
326326 init() {
327327 MacPro.resolve()
328 MacPro.renewInBackground()
328329 // Debug builds, and runs with ORGSTAR_PERF set: main-thread stalls in the console.
329330 #if DEBUG
330331 Perf.watchMainThread()
Sources/Orgstar/ProLicense.swift +27 −6
@@ -1,9 +1,10 @@
11import OrgApp
22import SwiftUI
33
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.
55enum MacPro {
66 static let buyURL = URL(string: "https://krz.sh/apps/orgstar/buy")!
7 static let keyURL = URL(string: "https://krz.sh/apps/orgstar/license")!
78
89 /// Sets `ProAccess.shared` from the stored license or an earlier free install.
910 @MainActor static func resolve() {
@@ -15,6 +16,18 @@ enum MacPro {
1516 ProAccess.shared.set(nil)
1617 }
1718 }
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 }
1831}
1932
2033/// Status, buying, and entering or removing a license key.
@@ -29,7 +42,12 @@ struct LicenseForm: View {
2942 Section {
3043 switch access.grant {
3144 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 }
3351 case .grandfathered:
3452 LabeledContent("orgstar+", value: "Included: you used orgstar before orgstar+")
3553 case .purchase, nil:
@@ -44,12 +62,13 @@ struct LicenseForm: View {
4462 .onSubmit(activate)
4563 if let error { Text(error).foregroundStyle(.red) }
4664 HStack {
47 Link("Buy orgstar+…", destination: MacPro.buyURL)
65 Link("Sponsor for orgstar+…", destination: MacPro.buyURL)
66 Link("Get Your Key…", destination: MacPro.keyURL)
4867 Spacer()
4968 Button("Activate", action: activate).disabled(key.trimmingCharacters(in: .whitespacesAndNewlines).isEmpty)
5069 }
5170 } 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.")
5372 }
5473 } else {
5574 Section {
@@ -76,7 +95,9 @@ struct LicenseForm: View {
7695 error = nil
7796 ProAccess.shared.set(.license)
7897 } 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."
80101 } catch {
81102 self.error = "That doesn't look like an orgstar license key."
82103 }
@@ -92,7 +113,7 @@ struct ProPaywallSheet: View {
92113 VStack(alignment: .leading, spacing: 0) {
93114 VStack(alignment: .leading, spacing: 6) {
94115 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.")
96117 .foregroundStyle(.secondary)
97118 }
98119 .padding([.horizontal, .top], 20)
Tests/OrgAppTests/ProAccessTests.swift +54 −1
@@ -84,7 +84,7 @@ struct LicenseKeyTests {
8484 @Test func verifiesASignedKey() throws {
8585 let text = try key(#"{"e":"a@example.com","t":"txn_01","i":1763000000}"#)
8686 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))
8888 }
8989
9090 @Test func ignoresWhitespaceFromPasting() throws {
@@ -116,6 +116,59 @@ struct LicenseKeyTests {
116116 _ = try Curve25519.Signing.PublicKey(rawRepresentation: raw)
117117 }
118118
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
119172 @Test func storesOnlyKeysThatVerify() throws {
120173 let defaults = try #require(UserDefaults(suiteName: "test.\(UUID().uuidString)"))
121174 #expect(throws: LicenseKey.Failure.malformed) { try LicenseStore.activate("nope", defaults: defaults) }
l10n/Localizable.xcstrings +173
@@ -4297,6 +4297,7 @@
42974297 }
42984298 },
42994299 "Buy orgstar+…": {
4300 "extractionState": "stale",
43004301 "localizations": {
43014302 "de": {
43024303 "stringUnit": {
@@ -12634,6 +12635,40 @@
1263412635 }
1263512636 }
1263612637 },
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 },
1263712672 "Git branch": {
1263812673 "localizations": {
1263912674 "de": {
@@ -23972,6 +24007,40 @@
2397224007 }
2397324008 }
2397424009 },
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 },
2397524044 "Reparent Note with Descendants…": {
2397624045 "comment": "Command title",
2397724046 "localizations": {
@@ -27828,6 +27897,74 @@
2782827897 }
2782927898 }
2783027899 },
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 },
2783127968 "Standard Mac editing keys, with Org commands on ⌃⌘: ⌃⌘T cycles TODO, ⌃⌘S schedules.": {
2783227969 "localizations": {
2783327970 "de": {
@@ -32570,6 +32707,7 @@
3257032707 }
3257132708 },
3257232709 "Your key is in the email from the purchase. It is checked on this Mac; nothing is sent.": {
32710 "extractionState": "stale",
3257332711 "localizations": {
3257432712 "de": {
3257532713 "stringUnit": {
@@ -34264,7 +34402,42 @@
3426434402 }
3426534403 }
3426634404 },
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 },
3426734439 "orgstar+ is a one-time purchase of $39.99 for this Mac. Editing, the agenda, capture, clocking and search stay free.": {
34440 "extractionState": "stale",
3426834441 "localizations": {
3426934442 "de": {
3427034443 "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.
2# Deployed Workers take them from `npx wrangler secret put NAME [--env sandbox]` instead.
3# Client-side token: test_… (sandbox) or live_…, from Paddle > Developer tools > Authentication.
4PADDLE_CLIENT_TOKEN=test_
5# API key with transaction.read and customer.read: pdl_sdbx_apikey_… (sandbox) or pdl_live_apikey_….
6PADDLE_API_KEY=
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` instead.
3# The GitHub OAuth app's client secret. For local runs, use a second OAuth app whose callback
4# URL is http://localhost:8787/license, and override GITHUB_CLIENT_ID here.
5GITHUB_CLIENT_SECRET=
6# A token of the SPONSORABLE account with read:user, for renewals (classic token, or
7# fine-grained with no repository access).
8GITHUB_TOKEN=
79# PKCS#8 PEM from keygen.sh, on one line with \n for line breaks.
810LICENSE_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.
2// Both paths are matched by their last segment, so the Worker answers under any route:
3// krz.sh/apps/orgstar/buy, krz.sh/apps/orgstar/sandbox/buy, or /buy under `wrangler dev`.
1// Issues orgstar+ for Mac license keys to GitHub sponsors. Paths are matched by their last
2// segment, so the Worker answers under any route: krz.sh/apps/orgstar/buy, or /buy under
3// `wrangler dev`.
44//
5// GET …/buy shows the price from Paddle.PricePreview, localized to the visitor's country (from
6// Cloudflare's request.cf, omitted when unknown so Paddle.js detects it from the IP), and opens
7// Paddle Checkout as a one-page overlay. On checkout.completed it goes to …/license?txn=txn_….
5// GET …/buy shows what orgstar+ includes and the two sponsorships that come with a key, linking to
6// github.com/sponsors/SPONSORABLE, and to …/license for a sponsor's key.
87//
9// GET …/license?txn=txn_… looks the transaction up in Paddle, and when it is completed and
10// includes PRICE_ID, returns `ORGSTAR1-<payload>.<signature>`: base64url JSON
11// {"e": email, "t": transaction, "i": billed-at seconds}, signed with Ed25519. The app checks the
12// signature offline (Sources/OrgApp/LicenseKey.swift). Ed25519 signatures are deterministic, so the
13// same transaction always yields the same key; nothing is stored.
8// GET …/license signs in with GitHub (OAuth, state in a cookie) and asks GitHub for the visitor's
9// sponsorship of SPONSORABLE:
10// - one-time, LIFETIME_DOLLARS or more: a key that doesn't expire, the same one each time;
11// - monthly and active, MONTHLY_DOLLARS or more: a key that expires RENEW_DAYS after it is issued.
1412//
15// Vars (wrangler.toml, per environment): PADDLE_ENV ("sandbox" or "production", no default), PRICE_ID.
16// Secrets (`wrangler secret put NAME [--env sandbox]`; locally .dev.vars, see .dev.vars.example):
17// PADDLE_CLIENT_TOKEN (test_… or live_…), PADDLE_API_KEY, LICENSE_PRIVATE_KEY (PKCS#8 PEM, from
18// keygen.sh; the sandbox Worker takes the same key).
19
20// The buy page's copy. The price comes from Paddle.
21const PRODUCT = {
22 name: "orgstar+ for Mac",
23 description: "One payment, a license key that doesn't expire. Editing, the agenda, capture, clocking, tables and search stay free.",
24 features: [
25 "Run and tangle source blocks",
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};
13// POST …/renew with a monthly key as the body returns a fresh one while that sponsorship is
14// still active (403 when it isn't). orgstar renews monthly keys in the background.
15//
16// A key is `ORGSTAR1-<payload>.<signature>`: base64url JSON {"e": GitHub login, "t": "github:" +
17// the account's node ID, "i": issued, "x": expires (monthly keys only), seconds}, signed with
18// Ed25519. The app checks it offline (Sources/OrgApp/LicenseKey.swift). Nothing is stored.
19//
20// Vars (wrangler.toml): SPONSORABLE, LIFETIME_DOLLARS, MONTHLY_DOLLARS, RENEW_DAYS,
21// GITHUB_CLIENT_ID. Secrets (`wrangler secret put NAME`; locally .dev.vars, see
22// .dev.vars.example): GITHUB_CLIENT_SECRET, GITHUB_TOKEN (SPONSORABLE's token, for renewals),
23// LICENSE_PRIVATE_KEY (PKCS#8 PEM, from keygen.sh).
3424
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];
3634
37/// Reads the settings a path needs and throws when one is missing or belongs to the other environment.
38function settings(env, ...needs) {
39 const api = PADDLE_API[env.PADDLE_ENV];
40 if (!api) throw new Error(`PADDLE_ENV must be "sandbox" or "production", not ${JSON.stringify(env.PADDLE_ENV)}`);
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)}`);
42 const prefix = env.PADDLE_ENV === "sandbox" ? "test_" : "live_";
43 if (needs.includes("token") && !env.PADDLE_CLIENT_TOKEN?.startsWith(prefix))
44 throw new Error(`PADDLE_CLIENT_TOKEN must be a ${prefix}… client-side token for ${env.PADDLE_ENV}`);
45 for (const name of ["PADDLE_API_KEY", "LICENSE_PRIVATE_KEY"])
46 if (needs.includes("issuer") && !env[name]) throw new Error(`${name} is not set`);
47 return { api, sandbox: env.PADDLE_ENV === "sandbox" };
35const STATE_COOKIE = "orgstar_state";
36
37/// Reads the settings and throws when one is missing.
38function settings(env, ...secrets) {
39 for (const name of ["SPONSORABLE", ...secrets])
40 if (!env[name]) throw new Error(`${name} is not set`);
41 const number = (name) => {
42 const value = Number(env[name]);
43 if (!(value > 0)) throw new Error(`${name} must be a positive number, not ${JSON.stringify(env[name])}`);
44 return value;
45 };
46 return {
47 sponsorable: env.SPONSORABLE,
48 lifetime: number("LIFETIME_DOLLARS"),
49 monthly: number("MONTHLY_DOLLARS"),
50 renewDays: number("RENEW_DAYS"),
51 };
4852}
4953
5054export default {
5155 async fetch(request, env) {
5256 const url = new URL(request.url);
53 if (url.pathname.endsWith("/buy")) return buy(request, env);
54 if (url.pathname.endsWith("/license")) return license(url, env);
57 if (url.pathname.endsWith("/buy")) return buy(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);
5560 return new Response("Not found", { status: 404 });
5661 },
5762};
5863
59function buy(request, env) {
60 const { sandbox } = settings(env, "token");
61 const country = request.cf?.country;
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("");
64function buy(url, env) {
65 const { sponsorable, lifetime, monthly } = settings(env);
66 const features = FEATURES.map((feature) => `<li>${feature}</li>`).join("");
7067 return page(
71 `<p>${PRODUCT.description}</p><ul>${features}</ul>` +
72 `<p class="price" id="price">Loading the price…</p>` +
73 `<button id="buy" type="button">Buy ${PRODUCT.name}</button>` +
74 `<p class="note">Checkout is by Paddle, the merchant of record. Your key shows on the next page.</p>` +
75 `<script src="https://cdn.paddle.com/paddle/v2/paddle.js"></script>` +
76 `<script>const config = ${JSON.stringify(config).replace(/</g, "\\u003c")};\n${BUY_SCRIPT}</script>`,
68 `<p>orgstar+ for Mac comes with sponsoring orgstar on GitHub. Editing, the agenda, capture, ` +
69 `clocking, tables and search stay free.</p><ul>${features}</ul>` +
70 `<ul class="tiers"><li><b>$${lifetime} once</b>: a license key that doesn't expire.</li>` +
71 `<li><b>$${monthly} a month</b>: a key that orgstar renews while you sponsor.</li></ul>` +
72 `<p><a class="button" href="https://github.com/sponsors/${sponsorable}">Sponsor on GitHub</a></p>` +
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>`,
7775 200,
78 PRODUCT.name,
76 "orgstar+ for Mac",
7977 );
8078}
8179
82// Runs on the buy page. Shows only Paddle's formatted total; does no price arithmetic.
83const BUY_SCRIPT = `
84if (config.sandbox) Paddle.Environment.set("sandbox");
85Paddle.Initialize({
86 token: config.token,
87 eventCallback(event) {
88 if (event.name === "checkout.completed")
89 location.href = new URL("license?txn=" + encodeURIComponent(event.data.transaction_id), location.href);
90 },
91});
92const items = [{ priceId: config.priceId, quantity: 1 }];
93const request = config.country ? { items, address: { countryCode: config.country } } : { items };
94Paddle.PricePreview(request)
95 .then((preview) => {
96 document.getElementById("price").textContent = preview.data.details.lineItems[0].formattedTotals.total;
97 })
98 .catch(() => {
99 document.getElementById("price").textContent = "The price shows at checkout.";
100 });
101document.getElementById("buy").onclick = () =>
102 Paddle.Checkout.open({ items, settings: { displayMode: "overlay", variant: "one-page" } });
103`;
80async function license(request, url, env) {
81 const config = settings(env, "GITHUB_CLIENT_ID", "GITHUB_CLIENT_SECRET", "LICENSE_PRIVATE_KEY");
82 const self = new URL(url.pathname, url);
83 const code = url.searchParams.get("code");
84 if (!code) {
85 const state = [...crypto.getRandomValues(new Uint8Array(16))].map((b) => b.toString(16).padStart(2, "0")).join("");
86 const authorize = new URL("https://github.com/login/oauth/authorize");
87 authorize.searchParams.set("client_id", env.GITHUB_CLIENT_ID);
88 authorize.searchParams.set("redirect_uri", self.href);
89 authorize.searchParams.set("scope", "read:user");
90 authorize.searchParams.set("state", state);
91 authorize.searchParams.set("allow_signup", "true");
92 return new Response(null, {
93 status: 302,
94 headers: {
95 location: authorize.href,
96 "set-cookie": `${STATE_COOKIE}=${state}; Path=${url.pathname}; Max-Age=600; HttpOnly; Secure; SameSite=Lax`,
97 },
98 });
99 }
104100
105async function license(url, env) {
106 const { api } = settings(env, "issuer");
107 const txn = url.searchParams.get("txn") ?? "";
108 if (!/^txn_[a-z0-9]{20,40}$/.test(txn)) return page("That isn't a Paddle transaction ID.", 400);
101 const cookie = (request.headers.get("cookie") ?? "").split(/;\s*/).find((c) => c.startsWith(STATE_COOKIE + "="));
102 if (!cookie || cookie.slice(STATE_COOKIE.length + 1) !== url.searchParams.get("state"))
103 return page(`The sign-in expired. <a href="${self}">Sign in again</a>.`, 400);
109104
110 const response = await fetch(`${api}/transactions/${txn}?include=customer`, {
111 headers: { Authorization: `Bearer ${env.PADDLE_API_KEY}` },
105 const exchange = await fetch("https://github.com/login/oauth/access_token", {
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 }),
112109 });
113 if (response.status === 404) return page("No purchase was found for that transaction.", 404);
114 if (!response.ok) return page("Paddle can't be reached right now. Try again in a minute.", 502);
115 const { data } = await response.json();
116 const paid = data.status === "completed" || data.status === "paid";
117 const forOrgstar = data.items?.some((item) => item.price?.id === env.PRICE_ID);
118 if (!paid || !forOrgstar) return page("That transaction isn't a completed orgstar+ purchase.", 404);
119
120 const key = await sign(
121 { e: data.customer?.email ?? "", t: txn, i: Math.floor(Date.parse(data.billed_at ?? data.created_at) / 1000) },
122 env.LICENSE_PRIVATE_KEY,
110 const token = exchange.ok ? (await exchange.json()).access_token : null;
111 if (!token) return page(`GitHub didn't complete the sign-in. <a href="${self}">Try again</a>.`, 502);
112
113 const data = await graphql(
114 token,
115 `query($login: String!) {
116 viewer { id login }
117 user(login: $login) {
118 sponsorshipForViewerAsSponsor(activeOnly: false) {
119 isActive createdAt tier { monthlyPriceInDollars isOneTime }
120 }
121 }
122 }`,
123 { login: config.sponsorable },
123124 );
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.`;
125148 return page(
126149 `<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; ` +
128 `the same link shows it again.</p>`,
150 `<p>In orgstar, open Settings ▸ orgstar+, paste the key and choose Activate. ${note}</p>`,
129151 200,
152 "orgstar+",
153 clear,
130154 );
131155}
132156
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
133215export async function sign(payload, pem) {
134 const der = Uint8Array.from(atob(pem.replace(/-----[^-]+-----|\s/g, "")), (c) => c.charCodeAt(0));
135 const privateKey = await crypto.subtle.importKey("pkcs8", der, { name: "Ed25519" }, false, ["sign"]);
216 const { privateKey } = await keys(pem);
136217 const body = new TextEncoder().encode(JSON.stringify(payload));
137218 const signature = new Uint8Array(await crypto.subtle.sign({ name: "Ed25519" }, privateKey, body));
138219 return `ORGSTAR1-${base64url(body)}.${base64url(signature)}`;
139220}
140221
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
141236function base64url(bytes) {
142237 return btoa(String.fromCharCode(...bytes)).replace(/\+/g, "-").replace(/\//g, "_").replace(/=+$/, "");
143238}
144239
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 = {}) {
146254 const html = `<!doctype html><meta charset="utf-8"><meta name="viewport" content="width=device-width">` +
147255 `<title>${heading}</title><style>body{font:16px/1.5 system-ui;max-width:40rem;margin:3rem auto;padding:0 1rem}` +
148256 `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}` +
150 `button{font:inherit;font-weight:600;padding:.7rem 1.4rem;border:0;border-radius:8px;background:#d4a017;color:#fff;cursor:pointer}</style>` +
257 `.tiers{list-style:none;padding:0}.note{color:#666;font-size:.9rem}` +
258 `.button{display:inline-block;font-weight:600;padding:.7rem 1.4rem;border-radius:8px;background:#d4a017;color:#fff;text-decoration:none}</style>` +
151259 `<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 } });
153261}
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 @@
11name = "orgstar-license"
22main = "worker.js"
33compatibility_date = "2026-10-01"
4# Paddle approves krz.sh as the live checkout domain.
54routes = [
65 { pattern = "krz.sh/apps/orgstar/buy*", zone_name = "krz.sh" },
76 { pattern = "krz.sh/apps/orgstar/license*", zone_name = "krz.sh" },
7 { pattern = "krz.sh/apps/orgstar/renew*", zone_name = "krz.sh" },
88]
99
1010[vars]
11PADDLE_ENV = "production"
12# The orgstar+ for Mac price in the live account, pri_…
13PRICE_ID = "pri_01m7c397a7ty57r349ye22exta"
14
15# npx wrangler deploy --env sandbox. The sandbox account's default payment link is
16# https://krz.sh/apps/orgstar/sandbox/buy.
17[env.sandbox]
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"
11SPONSORABLE = "ccleberg"
12LIFETIME_DOLLARS = "60"
13MONTHLY_DOLLARS = "5"
14# A monthly key lasts this long; the app renews it well before.
15RENEW_DAYS = "40"
16# The GitHub OAuth app's client ID. Its callback URL is https://krz.sh/apps/orgstar/license.
17GITHUB_CLIENT_ID = ""