Commit 65a97fc9c9

65a97fc9c9a3370a0d84c11f1152fd3ced3089b2

parent: af0ec3e6d1

Verified · cmc local/swift-test: success

cmc <hello@cleberg.net> · 2026-11-14 01:44 UTC

Add orgstar Pro: StoreKit on iOS, signed license keys on the Mac

Pro: running and tangling source blocks, export other than HTML and
Markdown (and publishing, rich-text copy), encrypting entries,
org-roam nodes, dailies and backlinks, widgets, the Watch app, the
clock Live Activity, Calendar and Reminders in the agenda, and
Shortcuts actions. Decrypting stays free.

- OrgApp: ProAccess (grant shared through the app group), ProFeature
  and the command/export mapping, Grandfathering, LicenseKey (Ed25519,
  verified offline) and LicenseStore.
- iOS: ProStore (monthly, yearly, lifetime; restore; manage), ProScreen
  and paywall sheet, Settings row, Orgstar.storekit wired into the
  scheme. Installs whose AppTransaction.originalAppVersion predates
  build 569 keep Pro.
- Mac: Settings > Pro license form and paywall sheet. Macs that ran
  an earlier version (Sparkle's first-launch flag or roots.json) keep
  Pro.
- packaging/license-issuer: Cloudflare Worker that signs a key for a
  completed Paddle transaction, keygen script, buy button snippet.
  release-mac.sh refuses to build while the public key is the
  placeholder.
- README and App Store description describe Pro.

Layout: unified · split

README.org +13
@@ -59,6 +59,19 @@ or download the notarized DMG from the
59[[https://gitbay.org/krz/orgstar/releases][releases page]]. The iPhone and iPad app (iOS 26 59[[https://gitbay.org/krz/orgstar/releases][releases page]]. The iPhone and iPad app (iOS 26
60or later), with its Apple Watch app, is on the [[https://apps.apple.com/us/app/orgstar-org-mode-agenda/id6821552018][App Store]]. 60or later), with its Apple Watch app, is on the [[https://apps.apple.com/us/app/orgstar-org-mode-agenda/id6821552018][App Store]].
61 61
62** orgstar Pro
63Editing, the agenda, capture, clocking, tables, search, and HTML and Markdown export are
64free. Pro adds running and tangling source blocks; PDF, LaTeX, ODT, Word and rich-text export
65and publishing; encrypting entries (decrypting stays free); org-roam nodes, daily notes and
66backlinks; widgets, the Apple Watch app and the clock Live Activity; Calendar and Reminders in
67the agenda; and Shortcuts actions.
68
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
71 Settings ▸ Pro.
72
73Anyone who installed orgstar before Pro keeps every feature without buying it.
74
62To build from source, contribute or release (the Mac app and the App Store), see 75To build from source, contribute or release (the Mac app and the App Store), see
63[[file:CONTRIBUTING.org]]. 76[[file:CONTRIBUTING.org]].
64 77
Sources/OrgApp/LicenseKey.swift added +79
@@ -0,0 +1,79 @@
1import CryptoKit
2import Foundation
3
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`.
6public 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.
10 public let transaction: String
11 /// When the key was issued, as Unix seconds.
12 public let issued: Int
13
14 enum CodingKeys: String, CodingKey {
15 case email = "e", transaction = "t", issued = "i"
16 }
17
18 public enum Failure: Error, Equatable {
19 case malformed, badSignature
20 }
21
22 static let prefix = "ORGSTAR1-"
23
24 /// The issuer's Ed25519 public key (raw, 32 bytes), base64. `packaging/license-issuer/keygen.sh`
25 /// writes it here; until then it is a placeholder whose private half was discarded, and
26 /// `scripts/release-mac.sh` refuses to build.
27 public static let publicKey = "HgdAY0pinMJiv7QslPxwinKr+NCpzoEGpObk7PsLtm4=" // placeholder
28
29 public init(email: String, transaction: String, issued: Int) {
30 self.email = email
31 self.transaction = transaction
32 self.issued = issued
33 }
34
35 /// Checks `text` (whitespace and line breaks from pasting are ignored) and returns the license.
36 public static func verify(_ text: String, publicKey: String = publicKey) throws(Failure) -> LicenseKey {
37 let key = text.filter { !$0.isWhitespace }
38 guard key.hasPrefix(prefix) else { throw .malformed }
39 let parts = key.dropFirst(prefix.count).split(separator: ".", omittingEmptySubsequences: false)
40 guard parts.count == 2,
41 let payload = Data(base64URL: String(parts[0])),
42 let signature = Data(base64URL: String(parts[1])),
43 let raw = Data(base64Encoded: publicKey),
44 let signer = try? Curve25519.Signing.PublicKey(rawRepresentation: raw)
45 else { throw .malformed }
46 guard signer.isValidSignature(signature, for: payload) else { throw .badSignature }
47 guard let license = try? JSONDecoder().decode(LicenseKey.self, from: payload) else { throw .malformed }
48 return license
49 }
50}
51
52/// The Mac app's stored license.
53public enum LicenseStore {
54 static let key = "pro.licenseKey"
55
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) }
59 }
60
61 /// 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)
64 defaults.set(text.filter { !$0.isWhitespace }, forKey: key)
65 return license
66 }
67
68 public static func remove(defaults: UserDefaults = .standard) {
69 defaults.removeObject(forKey: key)
70 }
71}
72
73extension Data {
74 init?(base64URL: String) {
75 var text = base64URL.replacingOccurrences(of: "-", with: "+").replacingOccurrences(of: "_", with: "/")
76 text += String(repeating: "=", count: (4 - text.count % 4) % 4)
77 self.init(base64Encoded: text)
78 }
79}
Sources/OrgApp/ProAccess.swift added +143
@@ -0,0 +1,143 @@
1import Foundation
2import Observation
3
4/// Features that need orgstar Pro.
5public enum ProFeature: String, CaseIterable, Sendable, Identifiable {
6 case babel, export, encryption, roam
7 case widgets, watch, liveActivity, calendar, shortcuts
8
9 public var id: String { rawValue }
10
11 public var title: String {
12 switch self {
13 case .babel: "Run and tangle source blocks"
14 case .export: "PDF, Word and other export, and publishing"
15 case .encryption: "Encrypted entries"
16 case .roam: "Org-roam nodes and backlinks"
17 case .widgets: "Widgets"
18 case .watch: "Apple Watch app"
19 case .liveActivity: "Clock Live Activity"
20 case .calendar: "Calendar and Reminders"
21 case .shortcuts: "Shortcuts actions"
22 }
23 }
24
25 public var systemImage: String {
26 switch self {
27 case .babel: "play.rectangle"
28 case .export: "square.and.arrow.up"
29 case .encryption: "lock"
30 case .roam: "point.3.connected.trianglepath.dotted"
31 case .widgets: "square.grid.2x2"
32 case .watch: "applewatch"
33 case .liveActivity: "timer"
34 case .calendar: "calendar"
35 case .shortcuts: "square.stack.3d.up"
36 }
37 }
38}
39
40extension ProFeature {
41 /// Export formats that stay free.
42 static let freeExports: Set<String> = ["html", "html-open", "markdown"]
43
44 /// The feature an export format needs, if any.
45 public static func required(byExport format: String) -> ProFeature? {
46 freeExports.contains(format) ? nil : .export
47 }
48
49 /// The feature an app command (`app.…`, from a key, menu or the palette) needs, if any.
50 /// Decrypting stays free so no one is locked out of their own text.
51 public static func required(byCommand id: String) -> ProFeature? {
52 switch id {
53 case "app.copy-rich-text": .export
54 case let id where id.hasPrefix("app.export."): required(byExport: String(id.dropFirst("app.export.".count)))
55 case let id where id.hasPrefix("app.publish"): .export
56 case "app.crypt.encrypt-entry", "app.crypt.encrypt-entries": .encryption
57 case let id where id.hasPrefix("app.dailies.") || id.hasPrefix("app.node."): .roam
58 case "app.toggle-backlinks", "app.backlinks": .roam
59 default: nil
60 }
61 }
62}
63
64/// Why Pro is unlocked.
65public enum ProGrant: String, Codable, Sendable {
66 /// Installed before Pro existed.
67 case grandfathered
68 /// An App Store purchase or subscription.
69 case purchase
70 /// A Mac license key.
71 case license
72}
73
74/// Whether Pro is unlocked. The app writes it; the app group's defaults carry it to the widgets,
75/// share extension and intents, which only read it.
76@MainActor @Observable
77public final class ProAccess {
78 public static let shared = ProAccess(defaults: ProAccess.groupDefaults)
79
80 nonisolated static let grantKey = "pro.grant"
81
82 /// The app group's defaults, or the standard ones when the app isn't in the group (the Mac app).
83 public nonisolated static var groupDefaults: UserDefaults {
84 UserDefaults(suiteName: CaptureInbox.group) ?? .standard
85 }
86
87 /// For code outside the main actor (widgets, intents): reads the stored grant.
88 public nonisolated static var isUnlockedNow: Bool {
89 groupDefaults.string(forKey: grantKey).flatMap(ProGrant.init(rawValue:)) != nil
90 }
91
92 private let defaults: UserDefaults
93 public private(set) var grant: ProGrant?
94 /// The feature whose paywall should show, if any.
95 public var paywall: ProFeature?
96
97 public init(defaults: UserDefaults) {
98 self.defaults = defaults
99 grant = defaults.string(forKey: Self.grantKey).flatMap(ProGrant.init(rawValue:))
100 }
101
102 public var isUnlocked: Bool { grant != nil }
103
104 public func set(_ grant: ProGrant?) {
105 self.grant = grant
106 defaults.set(grant?.rawValue, forKey: Self.grantKey)
107 }
108
109 /// True when `feature` may be used; otherwise shows its paywall and returns false.
110 @discardableResult
111 public func allows(_ feature: ProFeature) -> Bool {
112 if isUnlocked { return true }
113 paywall = feature
114 return false
115 }
116}
117
118/// Who installed before Pro and keeps it free.
119public enum Grandfathering {
120 /// The first iOS build (`CFBundleVersion`, the commit count) that sells Pro: one more than
121 /// main's count before Pro merged. An App Store `originalAppVersion` below it means the app was
122 /// first downloaded while it was free.
123 public static let firstPaidIOSBuild = 569
124
125 /// Whether an App Store original build number predates Pro.
126 public static func predatesPro(originalBuild: String, firstPaidBuild: Int = firstPaidIOSBuild) -> Bool {
127 guard let build = Int(originalBuild.trimmingCharacters(in: .whitespaces)) else { return false }
128 return build < firstPaidBuild
129 }
130
131 static let macDecidedKey = "pro.macGrandfatherDecided"
132
133 /// Decides once, on the first launch of a Pro build of the Mac app, whether this Mac ran an
134 /// earlier free version: Sparkle marks its first launch, and `marker` (the workspace's list of
135 /// folders) exists once folders were added. Later launches return the first answer.
136 public static func macPredatesPro(defaults: UserDefaults = .standard, marker: URL?) -> Bool {
137 if let decided = defaults.object(forKey: macDecidedKey) as? Bool { return decided }
138 let ranBefore = defaults.object(forKey: "SUHasLaunchedBefore") != nil
139 || marker.map { FileManager.default.fileExists(atPath: $0.path) } == true
140 defaults.set(ranBefore, forKey: macDecidedKey)
141 return ranBefore
142 }
143}
Sources/OrgApp/WidgetIntents.swift +1
@@ -73,6 +73,7 @@ public struct ClockToggleIntent: SetValueIntent, LiveActivityIntent {
73 public init() {} 73 public init() {}
74 74
75 public func perform() async throws -> some IntentResult { 75 public func perform() async throws -> some IntentResult {
76 guard ProAccess.isUnlockedNow else { return .result() }
76 let handler = await MainActor.run { Self.handler } 77 let handler = await MainActor.run { Self.handler }
77 await handler?(value) 78 await handler?(value)
78 return .result() 79 return .result()
Sources/OrgWatchData/WatchAgenda.swift +9
@@ -74,6 +74,15 @@ public struct WatchAgenda: Codable, Equatable, Sendable {
74 public var clock: Clock? 74 public var clock: Clock?
75 /// The most recently clocked entry, `org-clock-in-last`'s. 75 /// The most recently clocked entry, `org-clock-in-last`'s.
76 public var lastClocked: String? 76 public var lastClocked: String?
77 /// True when the phone hasn't got orgstar Pro, which the Watch app needs.
78 public var locked: Bool?
79
80 /// What the phone sends without Pro: no entries.
81 public static func locked(generated: Date) -> WatchAgenda {
82 var agenda = WatchAgenda(generated: generated, day: generated, overdue: [], rows: [], clock: nil, lastClocked: nil)
83 agenda.locked = true
84 return agenda
85 }
77 86
78 public init(generated: Date, day: Date, overdue: [Entry], rows: [Entry], clock: Clock?, lastClocked: String?) { 87 public init(generated: Date, day: Date, overdue: [Entry], rows: [Entry], clock: Clock?, lastClocked: String?) {
79 self.generated = generated 88 self.generated = generated
Sources/Orgstar/AgendaView.swift +3 −2
@@ -176,13 +176,13 @@ struct AgendaView: View {
176 agenda.options.logMode = logMode 176 agenda.options.logMode = logMode
177 agenda.options = OrgPreferences.agendaOptions(agenda.options) 177 agenda.options = OrgPreferences.agendaOptions(agenda.options)
178 agenda.calendarNames = OrgPreferences.calendarEventCalendars() 178 agenda.calendarNames = OrgPreferences.calendarEventCalendars()
179 if calendarEventsOn, isAgenda || isBlocks { 179 if calendarEventsOn, ProAccess.shared.isUnlocked, isAgenda || isBlocks {
180 agenda.calendarEvents = await CalendarAccess.events.requestAccess() ? CalendarAccess.events : nil 180 agenda.calendarEvents = await CalendarAccess.events.requestAccess() ? CalendarAccess.events : nil
181 } else { 181 } else {
182 agenda.calendarEvents = nil 182 agenda.calendarEvents = nil
183 } 183 }
184 agenda.reminderListNames = OrgPreferences.agendaReminderLists() 184 agenda.reminderListNames = OrgPreferences.agendaReminderLists()
185 if remindersOn, isAgenda || isBlocks { 185 if remindersOn, ProAccess.shared.isUnlocked, isAgenda || isBlocks {
186 agenda.reminderLists = await CalendarAccess.reminders.requestAccess() ? CalendarAccess.reminders : nil 186 agenda.reminderLists = await CalendarAccess.reminders.requestAccess() ? CalendarAccess.reminders : nil
187 } else { 187 } else {
188 agenda.reminderLists = nil 188 agenda.reminderLists = nil
@@ -601,6 +601,7 @@ struct AgendaView: View {
601 Button("Set Deadline…") { selection = line.id; run(SetPlanning(deadline: true)) } 601 Button("Set Deadline…") { selection = line.id; run(SetPlanning(deadline: true)) }
602 Divider() 602 Divider()
603 Button("Add to Calendar…") { 603 Button("Add to Calendar…") {
604 guard ProAccess.shared.allows(.calendar) else { return }
604 eventRequest = EventRequest(draft: .entry(line.row.title, day: line.day, start: line.row.start, end: line.row.end)) 605 eventRequest = EventRequest(draft: .entry(line.row.title, day: line.day, start: line.row.start, end: line.row.end))
605 } 606 }
606 Divider() 607 Divider()
Sources/Orgstar/CaptureIntent.swift +1
@@ -26,6 +26,7 @@ struct CaptureIntent: AppIntent {
26 @MainActor 26 @MainActor
27 func perform() async throws -> some IntentResult & ReturnsValue<String> & ProvidesDialog { 27 func perform() async throws -> some IntentResult & ReturnsValue<String> & ProvidesDialog {
28 // Launched for the intent, the window sets the models up shortly. 28 // Launched for the intent, the window sets the models up shortly.
29 guard ProAccess.shared.isUnlocked else { throw Failure(message: "Shortcuts actions need orgstar Pro") }
29 for _ in 0..<50 where Self.environment == nil { try? await Task.sleep(for: .milliseconds(100)) } 30 for _ in 0..<50 where Self.environment == nil { try? await Task.sleep(for: .milliseconds(100)) }
30 guard let (workspace, session, clock, commands) = Self.environment else { throw Failure(message: "orgstar isn't ready") } 31 guard let (workspace, session, clock, commands) = Self.environment else { throw Failure(message: "orgstar isn't ready") }
31 let placed = session.capture( 32 let placed = session.capture(
Sources/Orgstar/ContentView.swift +8 −3
@@ -341,6 +341,7 @@ struct ContentView: View {
341 .onChange(of: preset, initial: true) { loadKeymap() } 341 .onChange(of: preset, initial: true) { loadKeymap() }
342 .sheet(isPresented: $showingImport) { EmacsImportView(workspace: workspace) } 342 .sheet(isPresented: $showingImport) { EmacsImportView(workspace: workspace) }
343 .sheet(item: $panel) { panel in panelView(panel) } 343 .sheet(item: $panel) { panel in panelView(panel) }
344 .sheet(item: Bindable(ProAccess.shared).paywall) { feature in ProPaywallSheet(feature: feature) }
344 .sheet(item: $blockEdit) { request in 345 .sheet(item: $blockEdit) { request in
345 BlockEditorView(edit: request.edit) { content in 346 BlockEditorView(edit: request.edit) { content in
346 blockEdit = nil 347 blockEdit = nil
@@ -550,6 +551,7 @@ struct ContentView: View {
550 /// dispatcher does, or to `destination`, and opens it with `open`. `subtree` exports the 551 /// dispatcher does, or to `destination`, and opens it with `open`. `subtree` exports the
551 /// subtree at the caret alone; `bodyOnly` leaves out the title and page wrapper. 552 /// subtree at the caret alone; `bodyOnly` leaves out the title and page wrapper.
552 private func export(_ format: String, to destination: URL? = nil, open: Bool = false, subtree: Bool = false, bodyOnly: Bool = false) { 553 private func export(_ format: String, to destination: URL? = nil, open: Bool = false, subtree: Bool = false, bodyOnly: Bool = false) {
554 if let feature = ProFeature.required(byExport: format), !ProAccess.shared.allows(feature) { return }
553 if format == "icalendar-agenda" || format == "icalendar-combined" { return exportAgendaCalendars(combined: format == "icalendar-combined") } 555 if format == "icalendar-agenda" || format == "icalendar-combined" { return exportAgendaCalendars(combined: format == "icalendar-combined") }
554 guard let path = session.path, var text = session.document?.text else { 556 guard let path = session.path, var text = session.document?.text else {
555 commands.show("No file is open") 557 commands.show("No file is open")
@@ -860,6 +862,7 @@ struct ContentView: View {
860 DispatchQueue.main.async { commands.editor?.perform(SparseTreeCommand(), answers: ["sparse": "/", "regexp": regexp]) } 862 DispatchQueue.main.async { commands.editor?.perform(SparseTreeCommand(), answers: ["sparse": "/", "regexp": regexp]) }
861 } 863 }
862 case .tangle(let scope): 864 case .tangle(let scope):
865 guard ProAccess.shared.allows(.babel) else { return }
863 commands.show(session.tangle(scope)) 866 commands.show(session.tangle(scope))
864 case .agenda(let start, let days): 867 case .agenda(let start, let days):
865 commands.agendaRequest = (start, days) 868 commands.agendaRequest = (start, days)
@@ -886,6 +889,7 @@ struct ContentView: View {
886 } 889 }
887 } 890 }
888 case .babel(let job): 891 case .babel(let job):
892 guard ProAccess.shared.allows(.babel) else { return }
889 let run = { 893 let run = {
890 commands.show("Running \(job.language) block… (⌘. to cancel)") 894 commands.show("Running \(job.language) block… (⌘. to cancel)")
891 session.startBabel(job) { commands.show($0) } 895 session.startBabel(job) { commands.show($0) }
@@ -941,7 +945,7 @@ struct ContentView: View {
941 /// The desktop widgets' agenda and habits, written where the widget extension reads them, 945 /// The desktop widgets' agenda and habits, written where the widget extension reads them,
942 /// with the widgets reloaded when they changed. 946 /// with the widgets reloaded when they changed.
943 private func updateWidgets() async { 947 private func updateWidgets() async {
944 guard !Task.isCancelled, !workspace.files.isEmpty, let file = AgendaSnapshot.file() else { return } 948 guard !Task.isCancelled, ProAccess.shared.isUnlocked, !workspace.files.isEmpty, let file = AgendaSnapshot.file() else { return }
945 let days = widgetAgenda ?? AgendaModel(workspace: workspace) 949 let days = widgetAgenda ?? AgendaModel(workspace: workspace)
946 widgetAgenda = days 950 widgetAgenda = days
947 days.mode = .agenda(span: AgendaSnapshot.dayCount, startOffset: 0) 951 days.mode = .agenda(span: AgendaSnapshot.dayCount, startOffset: 0)
@@ -952,9 +956,9 @@ struct ContentView: View {
952 days.agendaFiles = OrgPreferences.agendaFiles() 956 days.agendaFiles = OrgPreferences.agendaFiles()
953 days.options = OrgPreferences.agendaOptions(days.options) 957 days.options = OrgPreferences.agendaOptions(days.options)
954 days.options.logMode = false 958 days.options.logMode = false
955 days.calendarEvents = OrgPreferences.calendarEvents() && CalendarEvents.isAuthorized ? CalendarAccess.events : nil 959 days.calendarEvents = ProAccess.shared.isUnlocked && OrgPreferences.calendarEvents() && CalendarEvents.isAuthorized ? CalendarAccess.events : nil
956 days.calendarNames = OrgPreferences.calendarEventCalendars() 960 days.calendarNames = OrgPreferences.calendarEventCalendars()
957 days.reminderLists = OrgPreferences.agendaReminders() && ReminderLists.isAuthorized ? CalendarAccess.reminders : nil 961 days.reminderLists = ProAccess.shared.isUnlocked && OrgPreferences.agendaReminders() && ReminderLists.isAuthorized ? CalendarAccess.reminders : nil
958 days.reminderListNames = OrgPreferences.agendaReminderLists() 962 days.reminderListNames = OrgPreferences.agendaReminderLists()
959 let open = session.openTexts 963 let open = session.openTexts
960 await days.refresh(open: open) 964 await days.refresh(open: open)
@@ -990,6 +994,7 @@ struct ContentView: View {
990 994
991 /// Runs a command from a key, the palette or the Org menu. 995 /// Runs a command from a key, the palette or the Org menu.
992 private func perform(_ id: String) { 996 private func perform(_ id: String) {
997 if let feature = ProFeature.required(byCommand: id), !ProAccess.shared.allows(feature) { return }
993 let orgOnly = ["app.refile", "app.refile.copy", "app.archive", "app.clock.in", "app.clock.default", "app.copy-rich-text"].contains(id) || (id.hasPrefix("app.export.") && !id.hasPrefix("app.export.icalendar-")) || id.hasPrefix("org.") 998 let orgOnly = ["app.refile", "app.refile.copy", "app.archive", "app.clock.in", "app.clock.default", "app.copy-rich-text"].contains(id) || (id.hasPrefix("app.export.") && !id.hasPrefix("app.export.icalendar-")) || id.hasPrefix("org.")
994 if orgOnly, !session.isOrg { 999 if orgOnly, !session.isOrg {
995 commands.show("Not an org file") 1000 commands.show("Not an org file")
Sources/Orgstar/OrgstarApp.swift +6
@@ -324,6 +324,7 @@ struct OrgstarApp: App {
324 }() 324 }()
325 325
326 init() { 326 init() {
327 MacPro.resolve()
327 // Debug builds, and runs with ORGSTAR_PERF set: main-thread stalls in the console. 328 // Debug builds, and runs with ORGSTAR_PERF set: main-thread stalls in the console.
328 #if DEBUG 329 #if DEBUG
329 Perf.watchMainThread() 330 Perf.watchMainThread()
@@ -649,6 +650,7 @@ struct SettingsView: View {
649 Tab("Appearance", systemImage: "paintpalette", value: "appearance") { appearance } 650 Tab("Appearance", systemImage: "paintpalette", value: "appearance") { appearance }
650 Tab("Agenda", systemImage: "calendar", value: "agenda") { agenda } 651 Tab("Agenda", systemImage: "calendar", value: "agenda") { agenda }
651 Tab("Capture", systemImage: "tray.and.arrow.down", value: "capture") { capture } 652 Tab("Capture", systemImage: "tray.and.arrow.down", value: "capture") { capture }
653 Tab("Pro", systemImage: "star", value: "pro") { LicenseForm() }
652 } 654 }
653 .frame(width: 600) 655 .frame(width: 600)
654 } 656 }
@@ -843,6 +845,8 @@ struct SettingsView: View {
843 } 845 }
844 Section { 846 Section {
845 Toggle("Show events from Calendar", isOn: $calendarEvents) 847 Toggle("Show events from Calendar", isOn: $calendarEvents)
848 .disabled(!ProAccess.shared.isUnlocked && !calendarEvents)
849 .help(ProAccess.shared.isUnlocked ? "" : "Needs orgstar Pro")
846 if calendarEvents { 850 if calendarEvents {
847 choices(calendars, empty: CalendarEvents.isAuthorized ? "No calendars." : "Allow orgstar to read your calendars in System Settings ▸ Privacy & Security ▸ Calendars.", setting: $calendarEventCalendars) 851 choices(calendars, empty: CalendarEvents.isAuthorized ? "No calendars." : "Allow orgstar to read your calendars in System Settings ▸ Privacy & Security ▸ Calendars.", setting: $calendarEventCalendars)
848 } 852 }
@@ -856,6 +860,8 @@ struct SettingsView: View {
856 } 860 }
857 Section { 861 Section {
858 Toggle("Show reminders from Reminders", isOn: $agendaReminders) 862 Toggle("Show reminders from Reminders", isOn: $agendaReminders)
863 .disabled(!ProAccess.shared.isUnlocked && !agendaReminders)
864 .help(ProAccess.shared.isUnlocked ? "" : "Needs orgstar Pro")
859 if agendaReminders { 865 if agendaReminders {
860 choices(reminderLists, empty: ReminderLists.isAuthorized ? "No lists." : "Allow orgstar to read your reminders in System Settings ▸ Privacy & Security ▸ Reminders.", setting: $agendaReminderLists) 866 choices(reminderLists, empty: ReminderLists.isAuthorized ? "No lists." : "Allow orgstar to read your reminders in System Settings ▸ Privacy & Security ▸ Reminders.", setting: $agendaReminderLists)
861 } 867 }
Sources/Orgstar/ProLicense.swift added +114
@@ -0,0 +1,114 @@
1import OrgApp
2import SwiftUI
3
4/// Pro on the Mac: a license key bought from the website, or an install that predates Pro.
5enum MacPro {
6 static let buyURL = URL(string: "https://krz.sh/apps/orgstar/buy")!
7
8 /// Sets `ProAccess.shared` from the stored license or an earlier free install.
9 @MainActor static func resolve() {
10 if LicenseStore.current() != nil {
11 ProAccess.shared.set(.license)
12 } else if Grandfathering.macPredatesPro(marker: WorkspaceModel.defaultDirectory.appendingPathComponent("roots.json")) {
13 ProAccess.shared.set(.grandfathered)
14 } else {
15 ProAccess.shared.set(nil)
16 }
17 }
18}
19
20/// Status, buying, and entering or removing a license key.
21struct LicenseForm: View {
22 @State private var key = ""
23 @State private var error: String?
24 @State private var license = LicenseStore.current()
25 private var access: ProAccess { ProAccess.shared }
26
27 var body: some View {
28 Form {
29 Section {
30 switch access.grant {
31 case .license:
32 LabeledContent("orgstar Pro", value: license.map { "Licensed to \($0.email)" } ?? "Licensed")
33 case .grandfathered:
34 LabeledContent("orgstar Pro", value: "Included: you used orgstar before Pro")
35 case .purchase, nil:
36 LabeledContent("orgstar Pro", value: "Not licensed")
37 }
38 }
39 if access.grant != .license {
40 Section {
41 TextField("License key", text: $key, prompt: Text("ORGSTAR1-…"), axis: .vertical)
42 .lineLimit(2...4)
43 .font(.body.monospaced())
44 .onSubmit(activate)
45 if let error { Text(error).foregroundStyle(.red) }
46 HStack {
47 Link("Buy orgstar Pro…", destination: MacPro.buyURL)
48 Spacer()
49 Button("Activate", action: activate).disabled(key.trimmingCharacters(in: .whitespacesAndNewlines).isEmpty)
50 }
51 } footer: {
52 Text("Your key is in the email from the purchase. It is checked on this Mac; nothing is sent.")
53 }
54 } else {
55 Section {
56 Button("Remove License from This Mac", role: .destructive) {
57 LicenseStore.remove()
58 license = nil
59 MacPro.resolve()
60 }
61 }
62 }
63 Section("Included in Pro") {
64 ForEach(ProFeature.macFeatures) { feature in
65 Label(feature.title, systemImage: feature.systemImage)
66 }
67 }
68 }
69 .formStyle(.grouped)
70 }
71
72 private func activate() {
73 do {
74 license = try LicenseStore.activate(key)
75 key = ""
76 error = nil
77 ProAccess.shared.set(.license)
78 } catch .badSignature {
79 error = "This key isn't valid for orgstar. Paste the whole key from the email."
80 } catch {
81 self.error = "That doesn't look like an orgstar license key."
82 }
83 }
84}
85
86/// Shown when a Pro feature is used without Pro.
87struct ProPaywallSheet: View {
88 let feature: ProFeature
89 @Environment(\.dismiss) private var dismiss
90
91 var body: some View {
92 VStack(alignment: .leading, spacing: 0) {
93 VStack(alignment: .leading, spacing: 6) {
94 Label("\(feature.title) needs orgstar Pro", systemImage: feature.systemImage).font(.headline)
95 Text("Pro is a one-time purchase of $39.99 for this Mac. Editing, the agenda, capture, clocking and search stay free.")
96 .foregroundStyle(.secondary)
97 }
98 .padding([.horizontal, .top], 20)
99 LicenseForm()
100 HStack {
101 Spacer()
102 Button("Done") { dismiss() }.keyboardShortcut(.defaultAction)
103 }
104 .padding([.horizontal, .bottom], 20)
105 }
106 .frame(width: 480, height: 520)
107 .onChange(of: ProAccess.shared.isUnlocked) { _, unlocked in if unlocked { dismiss() } }
108 }
109}
110
111extension ProFeature {
112 /// The Pro features the Mac app has.
113 static let macFeatures: [ProFeature] = [.babel, .export, .encryption, .roam, .widgets, .calendar, .shortcuts]
114}
Sources/OrgstarMobile/CaptureIntent.swift +1
@@ -23,6 +23,7 @@ struct CaptureIntent: AppIntent {
23 23
24 @MainActor 24 @MainActor
25 func perform() async throws -> some IntentResult & ReturnsValue<String> & ProvidesDialog { 25 func perform() async throws -> some IntentResult & ReturnsValue<String> & ProvidesDialog {
26 guard ProAccess.shared.isUnlocked else { throw Failure(message: "Shortcuts actions need orgstar Pro") }
26 let model = MobileModel.shared 27 let model = MobileModel.shared
27 guard let workspace = model.workspace else { throw Failure(message: model.failure ?? "orgstar isn't ready") } 28 guard let workspace = model.workspace else { throw Failure(message: model.failure ?? "orgstar isn't ready") }
28 let placed = model.session.capture( 29 let placed = model.session.capture(
Sources/OrgstarMobile/EditorScreen.swift +19 −12
@@ -136,18 +136,18 @@ struct EditorScreen: View {
136 Label("Show Markup", systemImage: "chevron.left.forwardslash.chevron.right") 136 Label("Show Markup", systemImage: "chevron.left.forwardslash.chevron.right")
137 } 137 }
138 RecentClockMenu(clock: clock) { editor?.run($0) } 138 RecentClockMenu(clock: clock) { editor?.run($0) }
139 Button("Backlinks", systemImage: "arrow.uturn.backward.circle") { sheet = .backlinks } 139 Button("Backlinks", systemImage: "arrow.uturn.backward.circle") { if ProAccess.shared.allows(.roam) { sheet = .backlinks } }
140 Menu("Daily Notes", systemImage: "calendar") { 140 Menu("Daily Notes", systemImage: "calendar") {
141 Button("Today", systemImage: "calendar") { roamActions.run("app.dailies.today") } 141 Button("Today", systemImage: "calendar") { roam("app.dailies.today") }
142 Button("Yesterday", systemImage: "chevron.backward") { roamActions.run("app.dailies.yesterday") } 142 Button("Yesterday", systemImage: "chevron.backward") { roam("app.dailies.yesterday") }
143 Button("Tomorrow", systemImage: "chevron.forward") { roamActions.run("app.dailies.tomorrow") } 143 Button("Tomorrow", systemImage: "chevron.forward") { roam("app.dailies.tomorrow") }
144 Button("Date…", systemImage: "calendar.badge.clock") { roamActions.run("app.dailies.date") } 144 Button("Date…", systemImage: "calendar.badge.clock") { roam("app.dailies.date") }
145 Button("Capture to Today", systemImage: "square.and.pencil") { roamActions.run("app.dailies.capture-today") } 145 Button("Capture to Today", systemImage: "square.and.pencil") { roam("app.dailies.capture-today") }
146 Button("Previous Daily Note", systemImage: "arrow.left") { roamActions.run("app.dailies.previous") } 146 Button("Previous Daily Note", systemImage: "arrow.left") { roam("app.dailies.previous") }
147 Button("Next Daily Note", systemImage: "arrow.right") { roamActions.run("app.dailies.next") } 147 Button("Next Daily Note", systemImage: "arrow.right") { roam("app.dailies.next") }
148 } 148 }
149 Button("Find Node…", systemImage: "point.3.connected.trianglepath.dotted") { roamActions.run("app.node.find") } 149 Button("Find Node…", systemImage: "point.3.connected.trianglepath.dotted") { roam("app.node.find") }
150 Button("Insert Node Link…", systemImage: "link") { roamActions.run("app.node.insert") } 150 Button("Insert Node Link…", systemImage: "link") { roam("app.node.insert") }
151 Menu("Attachments", systemImage: "paperclip") { 151 Menu("Attachments", systemImage: "paperclip") {
152 Button("Attach File…", systemImage: "doc.badge.plus") { attaching = .cp } 152 Button("Attach File…", systemImage: "doc.badge.plus") { attaching = .cp }
153 Button("Attach Photo or Video…", systemImage: "photo.badge.plus") { attachingPhotos = true } 153 Button("Attach Photo or Video…", systemImage: "photo.badge.plus") { attachingPhotos = true }
@@ -421,8 +421,8 @@ struct EditorScreen: View {
421 editor.onLink = { link in follow(link) } 421 editor.onLink = { link in follow(link) }
422 editor.onEditBlock = { edit in sheet = .block(edit) } 422 editor.onEditBlock = { edit in sheet = .block(edit) }
423 editor.onColumnView = { view in sheet = .columns(view) } 423 editor.onColumnView = { view in sheet = .columns(view) }
424 editor.onTangle = { scope in message = session.tangle(scope) } 424 editor.onTangle = { scope in if ProAccess.shared.allows(.babel) { message = session.tangle(scope) } }
425 editor.onBabel = { job in run(job) } 425 editor.onBabel = { job in if ProAccess.shared.allows(.babel) { run(job) } }
426 editor.onRefreshSetup = { session.refreshSetup() } 426 editor.onRefreshSetup = { session.refreshSetup() }
427 editor.onAgenda = { start, count in model.agendaRequest = .init(start: start, count: count) } 427 editor.onAgenda = { start, count in model.agendaRequest = .init(start: start, count: count) }
428 editor.keymap = model.keymap 428 editor.keymap = model.keymap
@@ -431,6 +431,7 @@ struct EditorScreen: View {
431 editor.onFiles = { attachActions.drop($0, method: .attach, attachMethod: .mv) } 431 editor.onFiles = { attachActions.drop($0, method: .attach, attachMethod: .mv) }
432 editor.onImage = { attachActions.yankImage($0, ext: $1) } 432 editor.onImage = { attachActions.yankImage($0, ext: $1) }
433 editor.onAppCommand = { id in 433 editor.onAppCommand = { id in
434 if let feature = ProFeature.required(byCommand: id), !ProAccess.shared.allows(feature) { return }
434 if Self.paneCommands.contains(id) { 435 if Self.paneCommands.contains(id) {
435 if let onPaneCommand { onPaneCommand(id) } else { message = "Not available here" } 436 if let onPaneCommand { onPaneCommand(id) } else { message = "Not available here" }
436 } else if id == "app.save" { 437 } else if id == "app.save" {
@@ -550,8 +551,14 @@ extension EditorScreen {
550 sheet = .exportSubtree(context.caret) 551 sheet = .exportSubtree(context.caret)
551 } 552 }
552 553
554 /// Org-roam's commands, with Pro.
555 private func roam(_ id: String) {
556 if ProAccess.shared.allows(.roam) { roamActions.run(id) }
557 }
558
553 /// org-crypt's commands at the caret, through the passphrase sheet. 559 /// org-crypt's commands at the caret, through the passphrase sheet.
554 private func crypt(_ id: String) { 560 private func crypt(_ id: String) {
561 if let feature = ProFeature.required(byCommand: id), !ProAccess.shared.allows(feature) { return }
555 guard let editor else { return } 562 guard let editor else { return }
556 let context = editor.editContext() 563 let context = editor.editContext()
557 switch id { 564 switch id {
Sources/OrgstarMobile/ExportMenu.swift +12 −5
@@ -12,6 +12,9 @@ struct OrgExport: Transferable {
12 enum Format: CaseIterable { 12 enum Format: CaseIterable {
13 case html, markdown, pdf, docx, rtf, plainText, icalendar 13 case html, markdown, pdf, docx, rtf, plainText, icalendar
14 14
15 /// Whether it needs Pro now: every format but HTML and Markdown, until Pro is unlocked.
16 @MainActor var locked: Bool { self != .html && self != .markdown && !ProAccess.shared.isUnlocked }
17
15 var name: String { 18 var name: String {
16 switch self { 19 switch self {
17 case .html: "HTML" 20 case .html: "HTML"
@@ -118,15 +121,19 @@ struct ExportMenu: View {
118 var body: some View { 121 var body: some View {
119 Menu("Export", systemImage: "square.and.arrow.up") { 122 Menu("Export", systemImage: "square.and.arrow.up") {
120 ForEach(OrgExport.Format.allCases, id: \.self) { format in 123 ForEach(OrgExport.Format.allCases, id: \.self) { format in
121 let export = OrgExport(text: text, path: path, format: format, settings: OrgPreferences.orgSettings(), 124 if format.locked {
122 codeStyle: HTMLCodeStyle(highlighter: MobileEditor.highlighter, theme: model.theme)) 125 Button("\(format.name) (Pro)") { ProAccess.shared.allows(.export) }
123 ShareLink(item: export, preview: SharePreview(export.fileName)) { Text(format.name) } 126 } else {
127 let export = OrgExport(text: text, path: path, format: format, settings: OrgPreferences.orgSettings(),
128 codeStyle: HTMLCodeStyle(highlighter: MobileEditor.highlighter, theme: model.theme))
129 ShareLink(item: export, preview: SharePreview(export.fileName)) { Text(format.name) }
130 }
124 } 131 }
125 if let exportSubtree { 132 if let exportSubtree {
126 Button("Export Subtree…", systemImage: "list.bullet.indent") { exportSubtree() } 133 Button("Export Subtree…", systemImage: "list.bullet.indent") { exportSubtree() }
127 } 134 }
128 Divider() 135 Divider()
129 Button("Copy as Rich Text", systemImage: "doc.on.doc") { copy() } 136 Button("Copy as Rich Text", systemImage: "doc.on.doc") { if ProAccess.shared.allows(.export) { copy() } }
130 } 137 }
131 } 138 }
132 139
@@ -155,7 +162,7 @@ struct SubtreeExportScreen: View {
155 162
156 var body: some View { 163 var body: some View {
157 NavigationStack { 164 NavigationStack {
158 List(OrgExport.Format.allCases, id: \.self) { format in 165 List(OrgExport.Format.allCases.filter { !$0.locked }, id: \.self) { format in
159 let export = OrgExport(text: text, path: path, format: format, settings: OrgPreferences.orgSettings(), 166 let export = OrgExport(text: text, path: path, format: format, settings: OrgPreferences.orgSettings(),
160 codeStyle: HTMLCodeStyle(highlighter: MobileEditor.highlighter, theme: model.theme), subtree: caret) 167 codeStyle: HTMLCodeStyle(highlighter: MobileEditor.highlighter, theme: model.theme), subtree: caret)
161 ShareLink(item: export, preview: SharePreview(export.fileName)) { Text(format.name) } 168 ShareLink(item: export, preview: SharePreview(export.fileName)) { Text(format.name) }
Sources/OrgstarMobile/FoldersScreen.swift +1
@@ -109,6 +109,7 @@ struct FoldersScreen: View {
109extension FoldersScreen { 109extension FoldersScreen {
110 /// A daily note, opened in the reader. 110 /// A daily note, opened in the reader.
111 private func dailies(_ id: String) { 111 private func dailies(_ id: String) {
112 guard ProAccess.shared.allows(.roam) else { return }
112 RoamActions(session: session, roots: { workspace.rootPaths }, nodes: { [] }, show: { workspace.lastError = $0 }, ask: { $1(nil) }, 113 RoamActions(session: session, roots: { workspace.rootPaths }, nodes: { [] }, show: { workspace.lastError = $0 }, ask: { $1(nil) },
113 open: { path, offset in model.openRequest = .offset(path, offset) }, insertLink: { _, _ in }, 114 open: { path, offset in model.openRequest = .offset(path, offset) }, insertLink: { _, _ in },
114 refresh: { Task { await workspace.refresh() } }).run(id) 115 refresh: { Task { await workspace.refresh() } }).run(id)
Sources/OrgstarMobile/LiveClock.swift +1 −1
@@ -22,7 +22,7 @@ enum LiveClock {
22 for activity in activities where running.map({ !shows(activity, $0) }) ?? true { 22 for activity in activities where running.map({ !shows(activity, $0) }) ?? true {
23 await activity.end(nil, dismissalPolicy: .immediate) 23 await activity.end(nil, dismissalPolicy: .immediate)
24 } 24 }
25 guard let running, !activities.contains(where: { shows($0, running) }), ActivityAuthorizationInfo().areActivitiesEnabled else { return } 25 guard await ProAccess.shared.isUnlocked, let running, !activities.contains(where: { shows($0, running) }), ActivityAuthorizationInfo().areActivitiesEnabled else { return }
26 let state = ClockActivityAttributes.ContentState(heading: running.heading, startedAt: running.startedAt) 26 let state = ClockActivityAttributes.ContentState(heading: running.heading, startedAt: running.startedAt)
27 _ = try? Activity.request( 27 _ = try? Activity.request(
28 attributes: ClockActivityAttributes(path: running.path, start: running.start), content: ActivityContent(state: state, staleDate: nil) 28 attributes: ClockActivityAttributes(path: running.path, start: running.start), content: ActivityContent(state: state, staleDate: nil)
Sources/OrgstarMobile/MobileModel.swift +9 −2
@@ -156,9 +156,9 @@ final class MobileModel {
156 agenda.excludeArchives = OrgPreferences.agendaExcludeArchives() 156 agenda.excludeArchives = OrgPreferences.agendaExcludeArchives()
157 agenda.agendaFiles = OrgPreferences.agendaFiles() 157 agenda.agendaFiles = OrgPreferences.agendaFiles()
158 agenda.options = OrgPreferences.agendaOptions(agenda.options) 158 agenda.options = OrgPreferences.agendaOptions(agenda.options)
159 agenda.calendarEvents = OrgPreferences.calendarEvents() ? calendarEvents : nil 159 agenda.calendarEvents = ProAccess.shared.isUnlocked && OrgPreferences.calendarEvents() ? calendarEvents : nil
160 agenda.calendarNames = OrgPreferences.calendarEventCalendars() 160 agenda.calendarNames = OrgPreferences.calendarEventCalendars()
161 agenda.reminderLists = OrgPreferences.agendaReminders() ? reminderLists : nil 161 agenda.reminderLists = ProAccess.shared.isUnlocked && OrgPreferences.agendaReminders() ? reminderLists : nil
162 agenda.reminderListNames = OrgPreferences.agendaReminderLists() 162 agenda.reminderListNames = OrgPreferences.agendaReminderLists()
163 } 163 }
164 settingsVersion += 1 164 settingsVersion += 1
@@ -308,6 +308,13 @@ final class MobileModel {
308 } 308 }
309 await days.refresh(open: session.openTexts) 309 await days.refresh(open: session.openTexts)
310 let groups = days.groups() 310 let groups = days.groups()
311 guard ProAccess.shared.isUnlocked else {
312 // Widgets read the flag and show that they need Pro.
313 WatchLink.shared.send(.locked(generated: Date()))
314 await updateBadge(OverdueBadge.counts(groups, today: days.today, days: AgendaSnapshot.dayCount))
315 WidgetCenter.shared.reloadAllTimelines()
316 return
317 }
311 WatchLink.shared.send(WatchAgenda(groups: groups, today: days.today, clock: clock.running, lastClocked: clock.history.first?.title, generated: Date())) 318 WatchLink.shared.send(WatchAgenda(groups: groups, today: days.today, clock: clock.running, lastClocked: clock.history.first?.title, generated: Date()))
312 await updateBadge(OverdueBadge.counts(groups, today: days.today, days: AgendaSnapshot.dayCount)) 319 await updateBadge(OverdueBadge.counts(groups, today: days.today, days: AgendaSnapshot.dayCount))
313 if (try? HabitSnapshot(habits: await days.habits(open: session.openTexts), theme: theme).write()) == true { WidgetCenter.shared.reloadTimelines(ofKind: "sh.krz.orgstar.habits") } 320 if (try? HabitSnapshot(habits: await days.habits(open: session.openTexts), theme: theme).write()) == true { WidgetCenter.shared.reloadTimelines(ofKind: "sh.krz.orgstar.habits") }
Sources/OrgstarMobile/OrgstarMobileApp.swift +7
@@ -19,6 +19,7 @@ struct OrgstarMobileApp: App {
19 if ProcessInfo.processInfo.environment["ORGSTAR_PERF"] != nil { Perf.watchMainThread() } 19 if ProcessInfo.processInfo.environment["ORGSTAR_PERF"] != nil { Perf.watchMainThread() }
20 #endif 20 #endif
21 LiveClock.install() 21 LiveClock.install()
22 ProStore.shared.start()
22 // Early, so that the watch's actions are taken when iOS wakes the app for them. 23 // Early, so that the watch's actions are taken when iOS wakes the app for them.
23 WatchLink.shared.activate(MobileModel.shared) 24 WatchLink.shared.activate(MobileModel.shared)
24 } 25 }
@@ -219,6 +220,12 @@ struct RootView: View {
219 } 220 }
220 .interactiveDismissDisabled() 221 .interactiveDismissDisabled()
221 } 222 }
223 .sheet(item: Bindable(ProAccess.shared).paywall) { ProSheet(feature: $0) }
224 .onChange(of: ProAccess.shared.isUnlocked) {
225 // Calendar and Reminders in the agenda, the widgets and the watch follow Pro.
226 model.reloadConfig()
227 Task { await model.updateWidgets() }
228 }
222 .sheet(item: Binding(get: { model.clockPrompts.pending }, set: { if $0 == nil { model.clockPrompts.answer(nil) } })) { pending in 229 .sheet(item: Binding(get: { model.clockPrompts.pending }, set: { if $0 == nil { model.clockPrompts.answer(nil) } })) { pending in
223 ClockPromptSheet(prompt: pending.prompt) { model.clockPrompts.answer($0) } 230 ClockPromptSheet(prompt: pending.prompt) { model.clockPrompts.answer($0) }
224 } 231 }
Sources/OrgstarMobile/ProStore.swift added +207
@@ -0,0 +1,207 @@
1#if os(iOS)
2import OrgApp
3import StoreKit
4import SwiftUI
5import UIKit
6
7/// orgstar Pro from the App Store: a monthly or yearly subscription, or a lifetime purchase. It
8/// keeps `ProAccess.shared` current; installs from before Pro keep it without buying.
9@MainActor @Observable
10final class ProStore {
11 static let shared = ProStore()
12
13 static let monthly = "sh.krz.orgstar.pro.monthly"
14 static let yearly = "sh.krz.orgstar.pro.yearly"
15 static let lifetime = "sh.krz.orgstar.pro.lifetime"
16 static let productIDs = [monthly, yearly, lifetime]
17
18 private(set) var products: [Product] = []
19 private(set) var activeProductID: String?
20 private(set) var busy = false
21 var message: String?
22
23 @ObservationIgnored private var updates: Task<Void, Never>?
24
25 private init() {}
26
27 /// Starts listening for transactions and checks what's owned. Call once at launch.
28 func start() {
29 guard updates == nil else { return }
30 updates = Task.detached(priority: .background) {
31 for await result in Transaction.updates {
32 guard case .verified(let transaction) = result else { continue }
33 await transaction.finish()
34 await ProStore.shared.refresh()
35 }
36 }
37 Task { await refresh() }
38 }
39
40 func loadProducts() async {
41 guard products.isEmpty else { return }
42 do {
43 let fetched = try await Product.products(for: Self.productIDs)
44 products = Self.productIDs.compactMap { id in fetched.first { $0.id == id } }
45 } catch {
46 message = "The App Store can't be reached right now."
47 }
48 }
49
50 /// Sets Pro from the current entitlements, or from the original download predating Pro.
51 func refresh() async {
52 var active: String?
53 for await result in Transaction.currentEntitlements {
54 guard case .verified(let transaction) = result, Self.productIDs.contains(transaction.productID),
55 transaction.revocationDate == nil else { continue }
56 if active == nil || transaction.productID == Self.lifetime { active = transaction.productID }
57 }
58 activeProductID = active
59 if active != nil {
60 ProAccess.shared.set(.purchase)
61 } else if await Self.predatesPro() {
62 ProAccess.shared.set(.grandfathered)
63 } else if ProAccess.shared.grant != .grandfathered {
64 // A cached grandfathered grant survives the App Store being unreachable.
65 ProAccess.shared.set(nil)
66 }
67 }
68
69 /// Whether this Apple Account first downloaded orgstar before Pro. Only the production App
70 /// Store reports real original versions; sandbox and Xcode always say "1.0".
71 private static func predatesPro() async -> Bool {
72 guard case .verified(let app) = try? await AppTransaction.shared, app.environment == .production else { return false }
73 return Grandfathering.predatesPro(originalBuild: app.originalAppVersion)
74 }
75
76 func buy(_ product: Product) async {
77 busy = true
78 defer { busy = false }
79 message = nil
80 do {
81 switch try await product.purchase() {
82 case .success(.verified(let transaction)):
83 await transaction.finish()
84 await refresh()
85 case .success(.unverified):
86 message = "The App Store couldn't verify the purchase."
87 case .pending:
88 message = "The purchase is waiting for approval."
89 case .userCancelled:
90 break
91 @unknown default:
92 break
93 }
94 } catch {
95 message = "The purchase didn't go through. \(error.localizedDescription)"
96 }
97 }
98
99 func restore() async {
100 busy = true
101 defer { busy = false }
102 message = nil
103 do {
104 try await AppStore.sync()
105 await refresh()
106 if !ProAccess.shared.isUnlocked { message = "No orgstar Pro purchase was found for this Apple Account." }
107 } catch {
108 message = "Restore didn't finish. \(error.localizedDescription)"
109 }
110 }
111}
112
113/// What Pro includes, its prices, and buying, restoring or managing it.
114struct ProScreen: View {
115 /// The feature that led here, if any.
116 var feature: ProFeature?
117 @Environment(\.dismiss) private var dismiss
118 @State private var managing = false
119 private var store: ProStore { .shared }
120 private var access: ProAccess { .shared }
121
122 var body: some View {
123 Form {
124 Section {
125 VStack(alignment: .leading, spacing: 6) {
126 if let feature, !access.isUnlocked {
127 Text("\(feature.title) needs orgstar Pro.").font(.headline)
128 }
129 Text(status).foregroundStyle(.secondary)
130 }
131 }
132 Section {
133 ForEach(ProFeature.allCases) { Label($0.title, systemImage: $0.systemImage) }
134 } header: {
135 Text("Included in Pro")
136 } footer: {
137 Text("Editing, the agenda, capture, clocking, tables and search stay free.")
138 }
139 if access.grant != .grandfathered, store.activeProductID != ProStore.lifetime {
140 Section {
141 if store.products.isEmpty {
142 ProgressView().frame(maxWidth: .infinity)
143 }
144 ForEach(store.products) { product in
145 Button { Task { await store.buy(product) } } label: {
146 LabeledContent {
147 Text(product.displayPrice + period(product)).monospacedDigit()
148 } label: {
149 Text(product.displayName)
150 if product.id == store.activeProductID { Text("Current plan") }
151 }
152 }
153 .disabled(store.busy || product.id == store.activeProductID)
154 }
155 } footer: {
156 Text("Subscriptions renew automatically until cancelled in your Apple Account settings, at least 24 hours before the period ends.")
157 }
158 }
159 Section {
160 Button("Restore Purchases") { Task { await store.restore() } }.disabled(store.busy)
161 if store.activeProductID == ProStore.monthly || store.activeProductID == ProStore.yearly {
162 Button("Manage Subscription") { managing = true }
163 }
164 Link("Terms of Use", destination: URL(string: "https://www.apple.com/legal/internet-services/itunes/dev/stdeula/")!)
165 Link("Privacy Policy", destination: URL(string: "https://krz.sh/privacy/orgstar/")!)
166 }
167 if let message = store.message {
168 Section { Text(message).foregroundStyle(.secondary) }
169 }
170 }
171 .navigationTitle("orgstar Pro")
172 .navigationBarTitleDisplayMode(.inline)
173 .manageSubscriptionsSheet(isPresented: $managing)
174 .task { await store.loadProducts() }
175 }
176
177 private var status: String {
178 switch access.grant {
179 case .grandfathered: "Pro is included: you downloaded orgstar before Pro. Thank you."
180 case .purchase: store.activeProductID == ProStore.lifetime ? "You own orgstar Pro." : "Your orgstar Pro subscription is active."
181 case .license, nil: "Pro adds power features and Apple integrations."
182 }
183 }
184
185 private func period(_ product: Product) -> String {
186 switch product.subscription?.subscriptionPeriod.unit {
187 case .month: " / month"
188 case .year: " / year"
189 default: ""
190 }
191 }
192}
193
194/// The paywall as a sheet, with a close button.
195struct ProSheet: View {
196 let feature: ProFeature
197 @Environment(\.dismiss) private var dismiss
198
199 var body: some View {
200 NavigationStack {
201 ProScreen(feature: feature)
202 .toolbar { ToolbarItem(placement: .cancellationAction) { Button("Close") { dismiss() } } }
203 }
204 .onChange(of: ProAccess.shared.isUnlocked) { _, unlocked in if unlocked { dismiss() } }
205 }
206}
207#endif
Sources/OrgstarMobile/SettingsScreen.swift +7
@@ -127,6 +127,11 @@ struct SettingsScreen: View {
127 LabeledContent("Font", value: font) 127 LabeledContent("Font", value: font)
128 } 128 }
129 Section { 129 Section {
130 NavigationLink {
131 ProScreen()
132 } label: {
133 Label("orgstar Pro", systemImage: "star")
134 }
130 NavigationLink { 135 NavigationLink {
131 AboutScreen(appIcon: appIcon) 136 AboutScreen(appIcon: appIcon)
132 } label: { 137 } label: {
@@ -158,6 +163,7 @@ struct SettingsScreen: View {
158 Toggle("Show Calendar Events", isOn: Binding { 163 Toggle("Show Calendar Events", isOn: Binding {
159 on 164 on
160 } set: { value in 165 } set: { value in
166 guard !value || ProAccess.shared.allows(.calendar) else { return }
161 model.set("calendarEvents", to: .bool(value)) 167 model.set("calendarEvents", to: .bool(value))
162 if value { Task { await requestCalendars() } } 168 if value { Task { await requestCalendars() } }
163 }) 169 })
@@ -197,6 +203,7 @@ struct SettingsScreen: View {
197 Toggle("Show Reminders", isOn: Binding { 203 Toggle("Show Reminders", isOn: Binding {
198 on 204 on
199 } set: { value in 205 } set: { value in
206 guard !value || ProAccess.shared.allows(.calendar) else { return }
200 model.set("agendaReminders", to: .bool(value)) 207 model.set("agendaReminders", to: .bool(value))
201 if value { Task { await requestReminders() } } 208 if value { Task { await requestReminders() } }
202 }) 209 })
Sources/OrgstarMobile/WatchLink.swift +1 −1
@@ -36,7 +36,7 @@ final class WatchLink: NSObject, WCSessionDelegate {
36 } 36 }
37 37
38 func perform(_ action: WatchAction) async { 38 func perform(_ action: WatchAction) async {
39 guard let model, let workspace = model.workspace else { return } 39 guard ProAccess.shared.isUnlocked, let model, let workspace = model.workspace else { return }
40 switch action { 40 switch action {
41 case .done(let path, let offset, let headingLine, let keyword): 41 case .done(let path, let offset, let headingLine, let keyword):
42 _ = model.session.perform(SetTodo(keyword: keyword), path: path, at: offset, expect: (offset, headingLine)) 42 _ = model.session.perform(SetTodo(keyword: keyword), path: path, at: offset, expect: (offset, headingLine))
Sources/OrgstarWatch/WatchApp.swift +12
@@ -97,6 +97,18 @@ struct AgendaList: View {
97 @State private var dictated = "" 97 @State private var dictated = ""
98 98
99 var body: some View { 99 var body: some View {
100 if link.agenda?.locked == true {
101 ScrollView {
102 Text("The Watch app needs orgstar Pro. Get it in orgstar on your iPhone, in Settings.")
103 .foregroundStyle(.secondary)
104 }
105 .navigationTitle("Today")
106 } else {
107 list
108 }
109 }
110
111 private var list: some View {
100 List { 112 List {
101 if let clock = link.agenda?.clock { 113 if let clock = link.agenda?.clock {
102 Section("Clocked In") { 114 Section("Clocked In") {
Sources/OrgstarWidgets/AgendaTimeline.swift +12 −1
@@ -2,6 +2,16 @@ import OrgApp
2import SwiftUI 2import SwiftUI
3import WidgetKit 3import WidgetKit
4 4
5/// Whether the app lacks Pro, which the widgets need. Only iOS shares the flag with the widgets;
6/// the Mac app stops writing their data instead.
7var widgetsLocked: Bool {
8 #if os(iOS)
9 !ProAccess.isUnlockedNow
10 #else
11 false
12 #endif
13}
14
5struct AgendaEntry: TimelineEntry { 15struct AgendaEntry: TimelineEntry {
6 let date: Date 16 let date: Date
7 /// Nil until the app has written one. 17 /// Nil until the app has written one.
@@ -24,7 +34,8 @@ struct AgendaProvider: TimelineProvider {
24 } 34 }
25 35
26 static func load() -> AgendaSnapshot? { 36 static func load() -> AgendaSnapshot? {
27 AgendaSnapshot.file().flatMap(AgendaSnapshot.read) 37 guard !widgetsLocked else { return nil }
38 return AgendaSnapshot.file().flatMap(AgendaSnapshot.read)
28 } 39 }
29 40
30 static func timeline(_ snapshot: AgendaSnapshot?, now: Date, calendar: Calendar = .current) -> Timeline<AgendaEntry> { 41 static func timeline(_ snapshot: AgendaSnapshot?, now: Date, calendar: Calendar = .current) -> Timeline<AgendaEntry> {
Sources/OrgstarWidgets/HabitsWidget.swift +3 −3
@@ -29,12 +29,12 @@ struct HabitProvider: TimelineProvider {
29 } 29 }
30 30
31 func getSnapshot(in context: Context, completion: @escaping (HabitEntry) -> Void) { 31 func getSnapshot(in context: Context, completion: @escaping (HabitEntry) -> Void) {
32 let snapshot = HabitSnapshot.read() 32 let snapshot = widgetsLocked ? nil : HabitSnapshot.read()
33 completion(HabitEntry(date: .now, snapshot: snapshot ?? (context.isPreview ? .sample(.now) : nil))) 33 completion(HabitEntry(date: .now, snapshot: snapshot ?? (context.isPreview ? .sample(.now) : nil)))
34 } 34 }
35 35
36 func getTimeline(in context: Context, completion: @escaping (Timeline<HabitEntry>) -> Void) { 36 func getTimeline(in context: Context, completion: @escaping (Timeline<HabitEntry>) -> Void) {
37 let snapshot = HabitSnapshot.read() 37 let snapshot = widgetsLocked ? nil : HabitSnapshot.read()
38 let midnight = Calendar.current.startOfDay(for: .now) 38 let midnight = Calendar.current.startOfDay(for: .now)
39 let dates = [Date.now] + (1...7).compactMap { Calendar.current.date(byAdding: .day, value: $0, to: midnight) } 39 let dates = [Date.now] + (1...7).compactMap { Calendar.current.date(byAdding: .day, value: $0, to: midnight) }
40 completion(Timeline(entries: dates.map { HabitEntry(date: $0, snapshot: snapshot) }, policy: .atEnd)) 40 completion(Timeline(entries: dates.map { HabitEntry(date: $0, snapshot: snapshot) }, policy: .atEnd))
@@ -53,7 +53,7 @@ struct HabitsView: View {
53 if let snapshot = entry.snapshot, !snapshot.habits.isEmpty { 53 if let snapshot = entry.snapshot, !snapshot.habits.isEmpty {
54 content(snapshot) 54 content(snapshot)
55 } else { 55 } else {
56 Text(entry.snapshot == nil ? "Open orgstar to show your habits here." : "No habits in the agenda. Give an entry STYLE: habit.") 56 Text(entry.snapshot == nil ? !widgetsLocked ? "Open orgstar to show your habits here." : "Widgets need orgstar Pro." : "No habits in the agenda. Give an entry STYLE: habit.")
57 .font(.caption) 57 .font(.caption)
58 .foregroundStyle(.secondary) 58 .foregroundStyle(.secondary)
59 .frame(maxWidth: .infinity, maxHeight: .infinity) 59 .frame(maxWidth: .infinity, maxHeight: .infinity)
Sources/OrgstarWidgets/TodayWidget.swift +1 −1
@@ -25,7 +25,7 @@ struct TodayView: View {
25 if let snapshot = entry.snapshot { 25 if let snapshot = entry.snapshot {
26 content(snapshot) 26 content(snapshot)
27 } else { 27 } else {
28 Text("Open orgstar to show your agenda here.") 28 Text(!widgetsLocked ? "Open orgstar to show your agenda here." : "Widgets need orgstar Pro.")
29 .font(.caption) 29 .font(.caption)
30 .foregroundStyle(.secondary) 30 .foregroundStyle(.secondary)
31 .frame(maxWidth: .infinity, maxHeight: .infinity) 31 .frame(maxWidth: .infinity, maxHeight: .infinity)
Sources/OrgstarWidgets/UpNextWidget.swift +1 −1
@@ -64,7 +64,7 @@ struct UpNextView: View {
64 } else { 64 } else {
65 VStack(alignment: .leading, spacing: 0) { 65 VStack(alignment: .leading, spacing: 0) {
66 Text("Agenda").font(.headline).widgetAccentable() 66 Text("Agenda").font(.headline).widgetAccentable()
67 Text(entry.snapshot == nil ? "Open orgstar" : "Nothing left today").font(.body) 67 Text(entry.snapshot == nil ? !widgetsLocked ? "Open orgstar" : "Needs orgstar Pro" : "Nothing left today").font(.body)
68 } 68 }
69 .frame(maxWidth: .infinity, alignment: .leading) 69 .frame(maxWidth: .infinity, alignment: .leading)
70 } 70 }
Tests/OrgAppTests/ProAccessTests.swift added +131
@@ -0,0 +1,131 @@
1import CryptoKit
2import Foundation
3import Testing
4@testable import OrgApp
5
6struct GrandfatheringTests {
7 @Test func buildsBeforeTheFirstPaidOnePredatePro() {
8 #expect(Grandfathering.predatesPro(originalBuild: "16", firstPaidBuild: 17))
9 #expect(Grandfathering.predatesPro(originalBuild: "1", firstPaidBuild: 17))
10 #expect(!Grandfathering.predatesPro(originalBuild: "17", firstPaidBuild: 17))
11 #expect(!Grandfathering.predatesPro(originalBuild: "40", firstPaidBuild: 17))
12 }
13
14 @Test func unparseableBuildsDoNotPredatePro() {
15 // Sandbox and Xcode report "1.0"; they must not unlock Pro.
16 #expect(!Grandfathering.predatesPro(originalBuild: "1.0", firstPaidBuild: 17))
17 #expect(!Grandfathering.predatesPro(originalBuild: "", firstPaidBuild: 17))
18 }
19
20 @Test func macDecidesOnceFromAnEarlierLaunch() throws {
21 let defaults = try #require(UserDefaults(suiteName: "test.\(UUID().uuidString)"))
22 defaults.set(true, forKey: "SUHasLaunchedBefore")
23 #expect(Grandfathering.macPredatesPro(defaults: defaults, marker: nil))
24 defaults.removeObject(forKey: "SUHasLaunchedBefore")
25 #expect(Grandfathering.macPredatesPro(defaults: defaults, marker: nil))
26 }
27
28 @Test func aNewMacDoesNotPredatePro() throws {
29 let defaults = try #require(UserDefaults(suiteName: "test.\(UUID().uuidString)"))
30 let missing = FileManager.default.temporaryDirectory.appendingPathComponent(UUID().uuidString)
31 #expect(!Grandfathering.macPredatesPro(defaults: defaults, marker: missing))
32 // A folder created after the first Pro launch doesn't change the answer.
33 try FileManager.default.createDirectory(at: missing, withIntermediateDirectories: true)
34 defer { try? FileManager.default.removeItem(at: missing) }
35 #expect(!Grandfathering.macPredatesPro(defaults: defaults, marker: missing))
36 }
37}
38
39struct ProFeatureTests {
40 @Test func commandsNeedTheirFeature() {
41 #expect(ProFeature.required(byCommand: "app.export.pdf") == .export)
42 #expect(ProFeature.required(byCommand: "app.export.docx") == .export)
43 #expect(ProFeature.required(byCommand: "app.publish-all") == .export)
44 #expect(ProFeature.required(byCommand: "app.copy-rich-text") == .export)
45 #expect(ProFeature.required(byCommand: "app.crypt.encrypt-entry") == .encryption)
46 #expect(ProFeature.required(byCommand: "app.dailies.today") == .roam)
47 #expect(ProFeature.required(byCommand: "app.node.find") == .roam)
48 #expect(ProFeature.required(byCommand: "app.toggle-backlinks") == .roam)
49 }
50
51 @Test func freeCommandsStayFree() {
52 for id in ["app.export.html", "app.export.html-open", "app.export.markdown", "app.crypt.open-entry",
53 "app.crypt.decrypt-entry", "app.crypt.forget-passphrase", "app.save", "app.refile", "app.clock.in"] {
54 #expect(ProFeature.required(byCommand: id) == nil, "\(id)")
55 }
56 }
57}
58
59@MainActor
60struct ProAccessTests {
61 @Test func gatesUntilGrantedAndRemembers() throws {
62 let defaults = try #require(UserDefaults(suiteName: "test.\(UUID().uuidString)"))
63 let access = ProAccess(defaults: defaults)
64 #expect(!access.allows(.babel))
65 #expect(access.paywall == .babel)
66 access.set(.purchase)
67 #expect(access.allows(.roam))
68 #expect(ProAccess(defaults: defaults).grant == .purchase)
69 access.set(nil)
70 #expect(!ProAccess(defaults: defaults).isUnlocked)
71 }
72}
73
74struct LicenseKeyTests {
75 let signer = Curve25519.Signing.PrivateKey()
76 var publicKey: String { signer.publicKey.rawRepresentation.base64EncodedString() }
77
78 func key(_ json: String, signedBy signer: Curve25519.Signing.PrivateKey? = nil) throws -> String {
79 let payload = Data(json.utf8)
80 let signature = try (signer ?? self.signer).signature(for: payload)
81 return "ORGSTAR1-" + payload.base64URL + "." + signature.base64URL
82 }
83
84 @Test func verifiesASignedKey() throws {
85 let text = try key(#"{"e":"a@example.com","t":"txn_01","i":1763000000}"#)
86 let license = try LicenseKey.verify(text, publicKey: publicKey)
87 #expect(license == LicenseKey(email: "a@example.com", transaction: "txn_01", issued: 1763000000))
88 }
89
90 @Test func ignoresWhitespaceFromPasting() throws {
91 let text = try key(#"{"e":"a@example.com","t":"txn_01","i":1}"#)
92 let wrapped = " " + text.prefix(30) + "\n" + text.dropFirst(30) + "\n"
93 #expect(try LicenseKey.verify(wrapped, publicKey: publicKey).transaction == "txn_01")
94 }
95
96 @Test func rejectsAnotherSignerAndTampering() throws {
97 let forged = try key(#"{"e":"a@example.com","t":"txn_01","i":1}"#, signedBy: Curve25519.Signing.PrivateKey())
98 #expect(throws: LicenseKey.Failure.badSignature) { try LicenseKey.verify(forged, publicKey: publicKey) }
99
100 let good = try key(#"{"e":"a@example.com","t":"txn_01","i":1}"#)
101 let signature = good.split(separator: ".")[1]
102 let other = Data(#"{"e":"b@example.com","t":"txn_01","i":1}"#.utf8).base64URL
103 #expect(throws: LicenseKey.Failure.badSignature) {
104 try LicenseKey.verify("ORGSTAR1-\(other).\(signature)", publicKey: publicKey)
105 }
106 }
107
108 @Test func rejectsMalformedKeys() {
109 for text in ["", "hello", "ORGSTAR1-", "ORGSTAR1-abc", "ORGSTAR2-abc.def", "ORGSTAR1-!!.??"] {
110 #expect(throws: LicenseKey.Failure.malformed) { try LicenseKey.verify(text, publicKey: publicKey) }
111 }
112 }
113
114 @Test func theShippedPublicKeyParses() throws {
115 let raw = try #require(Data(base64Encoded: LicenseKey.publicKey))
116 _ = try Curve25519.Signing.PublicKey(rawRepresentation: raw)
117 }
118
119 @Test func storesOnlyKeysThatVerify() throws {
120 let defaults = try #require(UserDefaults(suiteName: "test.\(UUID().uuidString)"))
121 #expect(throws: LicenseKey.Failure.malformed) { try LicenseStore.activate("nope", defaults: defaults) }
122 #expect(LicenseStore.current(defaults: defaults) == nil)
123 }
124}
125
126extension Data {
127 var base64URL: String {
128 base64EncodedString().replacingOccurrences(of: "+", with: "-").replacingOccurrences(of: "/", with: "_")
129 .replacingOccurrences(of: "=", with: "")
130 }
131}
ios/AppStore/metadata.md +11
@@ -39,6 +39,17 @@ AND MORE
39- Spotlight search and Quick Look previews of .org files 39- Spotlight search and Quick Look previews of .org files
40- Themes and settings read from the same configuration folder as the Mac app 40- Themes and settings read from the same configuration folder as the Mac app
41 41
42ORGSTAR PRO
43Editing, the agenda, capture, clocking, tables and search are free. Pro, monthly, yearly or as a one-time lifetime purchase, adds:
44- Running and tangling source blocks
45- PDF, Word and rich text export
46- Encrypted entries
47- Org-roam nodes, daily notes and backlinks
48- Widgets, the Apple Watch app and the clock Live Activity
49- Calendar events and reminders in the agenda
50- Shortcuts actions
51Everyone who downloaded orgstar before Pro keeps all of it.
52
42## Keywords 53## Keywords
43 54
44org-mode,emacs,outline,todo,agenda,plain text,notes,tasks,gtd,planner,journal,org file,clock 55org-mode,emacs,outline,todo,agenda,plain text,notes,tasks,gtd,planner,journal,org file,clock
ios/Orgstar.storekit added +100
@@ -0,0 +1,100 @@
1{
2 "appPolicies": {
3 "eula": "",
4 "policies": [
5 {
6 "locale": "en_US",
7 "policyText": "",
8 "policyURL": ""
9 }
10 ]
11 },
12 "identifier": "0B5DFA11",
13 "nonRenewingSubscriptions": [],
14 "products": [
15 {
16 "displayPrice": "39.99",
17 "familyShareable": true,
18 "internalID": "6700000003",
19 "localizations": [
20 {
21 "description": "orgstar Pro, once, for good",
22 "displayName": "Pro Lifetime",
23 "locale": "en_US"
24 }
25 ],
26 "productID": "sh.krz.orgstar.pro.lifetime",
27 "referenceName": "Pro Lifetime",
28 "type": "NonConsumable"
29 }
30 ],
31 "settings": {
32 "_askToBuyEnabled": false,
33 "_billingGracePeriodEnabled": false,
34 "_billingIssuesEnabled": false,
35 "_disableDialogs": false,
36 "_failTransactionsEnabled": false,
37 "_locale": "en_US",
38 "_renewalBillingIssuesEnabled": false,
39 "_storefront": "USA",
40 "_storeKitErrors": [],
41 "_timeRate": 0
42 },
43 "subscriptionGroups": [
44 {
45 "id": "21600001",
46 "localizations": [],
47 "name": "orgstar Pro",
48 "subscriptions": [
49 {
50 "adHocOffers": [],
51 "codeOffers": [],
52 "displayPrice": "19.99",
53 "familyShareable": true,
54 "groupNumber": 1,
55 "internalID": "6700000002",
56 "introductoryOffers": [],
57 "localizations": [
58 {
59 "description": "Power features and Apple integrations",
60 "displayName": "Pro Yearly",
61 "locale": "en_US"
62 }
63 ],
64 "productID": "sh.krz.orgstar.pro.yearly",
65 "recurringSubscriptionPeriod": "P1Y",
66 "referenceName": "Pro Yearly",
67 "subscriptionGroupID": "21600001",
68 "type": "RecurringSubscription",
69 "winbackOffers": []
70 },
71 {
72 "adHocOffers": [],
73 "codeOffers": [],
74 "displayPrice": "1.99",
75 "familyShareable": true,
76 "groupNumber": 1,
77 "internalID": "6700000001",
78 "introductoryOffers": [],
79 "localizations": [
80 {
81 "description": "Power features and Apple integrations",
82 "displayName": "Pro Monthly",
83 "locale": "en_US"
84 }
85 ],
86 "productID": "sh.krz.orgstar.pro.monthly",
87 "recurringSubscriptionPeriod": "P1M",
88 "referenceName": "Pro Monthly",
89 "subscriptionGroupID": "21600001",
90 "type": "RecurringSubscription",
91 "winbackOffers": []
92 }
93 ]
94 }
95 ],
96 "version": {
97 "major": 4,
98 "minor": 0
99 }
100}
ios/Orgstar.xcodeproj/xcshareddata/xcschemes/Orgstar iOS.xcscheme +3
@@ -57,6 +57,9 @@
57 isEnabled = "YES"> 57 isEnabled = "YES">
58 </EnvironmentVariable> 58 </EnvironmentVariable>
59 </EnvironmentVariables> 59 </EnvironmentVariables>
60 <StoreKitConfigurationFileReference
61 identifier = "../../Orgstar.storekit">
62 </StoreKitConfigurationFileReference>
60 </LaunchAction> 63 </LaunchAction>
61 <ProfileAction 64 <ProfileAction
62 buildConfiguration = "Release" 65 buildConfiguration = "Release"
packaging/license-issuer/buy.html added +15
@@ -0,0 +1,15 @@
1<!-- The Buy button for krz.sh/apps/orgstar/buy (the domain Paddle approves). Fill in the client
2 token and price ID; after checkout the buyer lands on the Worker's page with their key. -->
3<script src="https://cdn.paddle.com/paddle/v2/paddle.js"></script>
4<button id="buy">Buy orgstar Pro for Mac, $39.99</button>
5<script>
6 const ISSUER = "https://orgstar-license.REPLACE_ME.workers.dev/license";
7 Paddle.Initialize({
8 token: "live_REPLACE_ME",
9 eventCallback(event) {
10 if (event.name === "checkout.completed") location.href = `${ISSUER}?txn=${event.data.transaction_id}`;
11 },
12 });
13 document.getElementById("buy").onclick = () =>
14 Paddle.Checkout.open({ items: [{ priceId: "pri_REPLACE_ME", quantity: 1 }] });
15</script>
packaging/license-issuer/keygen.sh added +14
@@ -0,0 +1,14 @@
1#!/bin/sh
2# Makes the license signing key pair once: stores the private key as the Worker's
3# LICENSE_PRIVATE_KEY secret and writes the public key into Sources/OrgApp/LicenseKey.swift.
4# The private key is never written to disk; keep a copy in a password manager when prompted.
5# Usage: packaging/license-issuer/keygen.sh
6set -eu
7cd "$(dirname "$0")"
8pem="$(openssl genpkey -algorithm ed25519)"
9public="$(printf '%s\n' "$pem" | openssl pkey -pubout -outform DER | tail -c 32 | base64)"
10printf '%s\n' "$pem" | npx wrangler secret put LICENSE_PRIVATE_KEY
11sed -i '' "s|public static let publicKey = .*|public static let publicKey = \"$public\"|" ../../Sources/OrgApp/LicenseKey.swift
12echo "Public key $public written to Sources/OrgApp/LicenseKey.swift; commit it."
13echo "Back up the private key now (it is not saved anywhere else):"
14printf '%s\n' "$pem"
packaging/license-issuer/worker.js added +61
@@ -0,0 +1,61 @@
1// Issues orgstar Mac license keys for completed Paddle transactions.
2//
3// GET /license?txn=txn_… looks the transaction up in Paddle, and when it is completed and
4// includes PRICE_ID, returns `ORGSTAR1-<payload>.<signature>`: base64url JSON
5// {"e": email, "t": transaction, "i": billed-at seconds}, signed with Ed25519. The app checks the
6// signature offline (Sources/OrgApp/LicenseKey.swift). Ed25519 signatures are deterministic, so the
7// same transaction always yields the same key; nothing is stored.
8//
9// Secrets (wrangler secret put): PADDLE_API_KEY, LICENSE_PRIVATE_KEY (PKCS#8 PEM, from keygen.sh).
10// Vars (wrangler.toml): PADDLE_API, PRICE_ID.
11
12export default {
13 async fetch(request, env) {
14 const url = new URL(request.url);
15 if (url.pathname !== "/license") return new Response("Not found", { status: 404 });
16 const txn = url.searchParams.get("txn") ?? "";
17 if (!/^txn_[a-z0-9]{20,40}$/.test(txn)) return page("That isn't a Paddle transaction ID.", 400);
18
19 const response = await fetch(`${env.PADDLE_API}/transactions/${txn}?include=customer`, {
20 headers: { Authorization: `Bearer ${env.PADDLE_API_KEY}` },
21 });
22 if (response.status === 404) return page("No purchase was found for that transaction.", 404);
23 if (!response.ok) return page("Paddle can't be reached right now. Try again in a minute.", 502);
24 const { data } = await response.json();
25 const paid = data.status === "completed" || data.status === "paid";
26 const forOrgstar = data.items?.some((item) => item.price?.id === env.PRICE_ID);
27 if (!paid || !forOrgstar) return page("That transaction isn't a completed orgstar Pro purchase.", 404);
28
29 const key = await sign(
30 { e: data.customer?.email ?? "", t: txn, i: Math.floor(Date.parse(data.billed_at ?? data.created_at) / 1000) },
31 env.LICENSE_PRIVATE_KEY,
32 );
33 if (url.searchParams.get("format") === "text") return new Response(key + "\n");
34 return page(
35 `<p>Your orgstar Pro license key:</p><pre>${key}</pre>` +
36 `<p>In orgstar, open Settings ▸ Pro, paste the key and choose Activate. Keep this page or the key; ` +
37 `the same link shows it again.</p>`,
38 200,
39 );
40 },
41};
42
43export async function sign(payload, pem) {
44 const der = Uint8Array.from(atob(pem.replace(/-----[^-]+-----|\s/g, "")), (c) => c.charCodeAt(0));
45 const privateKey = await crypto.subtle.importKey("pkcs8", der, { name: "Ed25519" }, false, ["sign"]);
46 const body = new TextEncoder().encode(JSON.stringify(payload));
47 const signature = new Uint8Array(await crypto.subtle.sign({ name: "Ed25519" }, privateKey, body));
48 return `ORGSTAR1-${base64url(body)}.${base64url(signature)}`;
49}
50
51function base64url(bytes) {
52 return btoa(String.fromCharCode(...bytes)).replace(/\+/g, "-").replace(/\//g, "_").replace(/=+$/, "");
53}
54
55function page(body, status) {
56 const html = `<!doctype html><meta charset="utf-8"><meta name="viewport" content="width=device-width">` +
57 `<title>orgstar Pro</title><style>body{font:16px/1.5 system-ui;max-width:40rem;margin:3rem auto;padding:0 1rem}` +
58 `pre{white-space:pre-wrap;word-break:break-all;background:#f4f4f4;padding:1rem;border-radius:6px}</style>` +
59 `<h1>orgstar Pro</h1>${body.startsWith("<") ? body : `<p>${body}</p>`}`;
60 return new Response(html, { status, headers: { "content-type": "text/html; charset=utf-8" } });
61}
packaging/license-issuer/wrangler.toml added +9
@@ -0,0 +1,9 @@
1name = "orgstar-license"
2main = "worker.js"
3compatibility_date = "2026-10-01"
4
5[vars]
6# https://sandbox-api.paddle.com while testing.
7PADDLE_API = "https://api.paddle.com"
8# The orgstar Pro (Mac) price, pri_…
9PRICE_ID = "pri_REPLACE_ME"
scripts/release-mac.sh +2
@@ -24,6 +24,8 @@ tap="${ORGSTAR_TAP:-../homebrew-tap}"
24publish="${ORGSTAR_PUBLISH:-1}" 24publish="${ORGSTAR_PUBLISH:-1}"
25sign="${ORGSTAR_SIGN:-$(security find-identity -v -p codesigning | sed -n 's/.*"\(Developer ID Application: .*\)"/\1/p' | head -1)}" 25sign="${ORGSTAR_SIGN:-$(security find-identity -v -p codesigning | sed -n 's/.*"\(Developer ID Application: .*\)"/\1/p' | head -1)}"
26[ -n "$sign" ] || { echo "No Developer ID Application identity in the keychain." >&2; exit 1; } 26[ -n "$sign" ] || { echo "No Developer ID Application identity in the keychain." >&2; exit 1; }
27! grep -q 'publicKey = .*// placeholder' Sources/OrgApp/LicenseKey.swift ||
28 { echo "Run packaging/license-issuer/keygen.sh first: the license public key is a placeholder." >&2; exit 1; }
27# The Sparkle public key; its private half is in the release Mac's login keychain (generate_keys). 29# The Sparkle public key; its private half is in the release Mac's login keychain (generate_keys).
28export ORGSTAR_ED_PUBLIC_KEY="${ORGSTAR_ED_PUBLIC_KEY:-StvsRDaDoGd4S/G66l7XHAcd3KPlpJlu0Gsv9GemsSo=}" 30export ORGSTAR_ED_PUBLIC_KEY="${ORGSTAR_ED_PUBLIC_KEY:-StvsRDaDoGd4S/G66l7XHAcd3KPlpJlu0Gsv9GemsSo=}"
29notes="Universal (Apple silicon and Intel), macOS 26 or later. Notarized." 31notes="Universal (Apple silicon and Intel), macOS 26 or later. Notarized."