Buy page in the license Worker; Paddle sandbox environment !380

merged merged by cmc on 2026-11-14 03:31 UTC · krz/orgstar:paddle-sandbox into main

5 files changed, +154 −51

Layout: unified · split

packaging/license-issuer/.dev.vars.example added +8
@@ -0,0 +1,8 @@
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=
7# PKCS#8 PEM from keygen.sh, on one line with \n for line breaks.
8LICENSE_PRIVATE_KEY=
packaging/license-issuer/.gitignore added +4
@@ -0,0 +1,4 @@
1.dev.vars
2.dev.vars.*
3!.dev.vars.example
4.wrangler/
packaging/license-issuer/buy.html deleted −15
@@ -1,15 +0,0 @@
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+ 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/worker.js +125 −33
@@ -1,45 +1,135 @@
1// Issues orgstar Mac license keys for completed Paddle transactions. 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`.
2// 4//
3// GET /license?txn=txn_… looks the transaction up in Paddle, and when it is completed and 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_….
8//
9// 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 10// 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 11// {"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 12// signature offline (Sources/OrgApp/LicenseKey.swift). Ed25519 signatures are deterministic, so the
7// same transaction always yields the same key; nothing is stored. 13// same transaction always yields the same key; nothing is stored.
8// 14//
9// Secrets (wrangler secret put): PADDLE_API_KEY, LICENSE_PRIVATE_KEY (PKCS#8 PEM, from keygen.sh). 15// Vars (wrangler.toml, per environment): PADDLE_ENV ("sandbox" or "production", no default), PRICE_ID.
10// Vars (wrangler.toml): PADDLE_API, 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};
34
35const PADDLE_API = { sandbox: "https://sandbox-api.paddle.com", production: "https://api.paddle.com" };
36
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" };
48}
11 49
12export default { 50export default {
13 async fetch(request, env) { 51 async fetch(request, env) {
14 const url = new URL(request.url); 52 const url = new URL(request.url);
15 if (url.pathname !== "/license") return new Response("Not found", { status: 404 }); 53 if (url.pathname.endsWith("/buy")) return buy(request, env);
16 const txn = url.searchParams.get("txn") ?? ""; 54 if (url.pathname.endsWith("/license")) return license(url, env);
17 if (!/^txn_[a-z0-9]{20,40}$/.test(txn)) return page("That isn't a Paddle transaction ID.", 400); 55 return new Response("Not found", { status: 404 });
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+ 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+ license key:</p><pre>${key}</pre>` +
36 `<p>In orgstar, open Settings ▸ orgstar+, paste the key and choose Activate. Keep this page or the key; ` +
37 `the same link shows it again.</p>`,
38 200,
39 );
40 }, 56 },
41}; 57};
42 58
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("");
70 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>`,
77 200,
78 PRODUCT.name,
79 );
80}
81
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`;
104
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);
109
110 const response = await fetch(`${api}/transactions/${txn}?include=customer`, {
111 headers: { Authorization: `Bearer ${env.PADDLE_API_KEY}` },
112 });
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,
123 );
124 if (url.searchParams.get("format") === "text") return new Response(key + "\n");
125 return page(
126 `<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>`,
129 200,
130 );
131}
132
43export async function sign(payload, pem) { 133export async function sign(payload, pem) {
44 const der = Uint8Array.from(atob(pem.replace(/-----[^-]+-----|\s/g, "")), (c) => c.charCodeAt(0)); 134 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"]); 135 const privateKey = await crypto.subtle.importKey("pkcs8", der, { name: "Ed25519" }, false, ["sign"]);
@@ -52,10 +142,12 @@ function base64url(bytes) {
52 return btoa(String.fromCharCode(...bytes)).replace(/\+/g, "-").replace(/\//g, "_").replace(/=+$/, ""); 142 return btoa(String.fromCharCode(...bytes)).replace(/\+/g, "-").replace(/\//g, "_").replace(/=+$/, "");
53} 143}
54 144
55function page(body, status) { 145function page(body, status, heading = "orgstar+") {
56 const html = `<!doctype html><meta charset="utf-8"><meta name="viewport" content="width=device-width">` + 146 const html = `<!doctype html><meta charset="utf-8"><meta name="viewport" content="width=device-width">` +
57 `<title>orgstar+</title><style>body{font:16px/1.5 system-ui;max-width:40rem;margin:3rem auto;padding:0 1rem}` + 147 `<title>${heading}</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>` + 148 `pre{white-space:pre-wrap;word-break:break-all;background:#f4f4f4;padding:1rem;border-radius:6px}` +
59 `<h1>orgstar+</h1>${body.startsWith("<") ? body : `<p>${body}</p>`}`; 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>` +
151 `<h1>${heading}</h1>${body.startsWith("<") ? body : `<p>${body}</p>`}`;
60 return new Response(html, { status, headers: { "content-type": "text/html; charset=utf-8" } }); 152 return new Response(html, { status, headers: { "content-type": "text/html; charset=utf-8" } });
61} 153}
packaging/license-issuer/wrangler.toml +17 −3
@@ -1,9 +1,23 @@
1name = "orgstar-license" 1name = "orgstar-license"
2main = "worker.js" 2main = "worker.js"
3compatibility_date = "2026-10-01" 3compatibility_date = "2026-10-01"
4# Paddle approves krz.sh as the live checkout domain.
5routes = [
6 { pattern = "krz.sh/apps/orgstar/buy*", zone_name = "krz.sh" },
7 { pattern = "krz.sh/apps/orgstar/license*", zone_name = "krz.sh" },
8]
4 9
5[vars] 10[vars]
6# https://sandbox-api.paddle.com while testing. 11PADDLE_ENV = "production"
7PADDLE_API = "https://api.paddle.com" 12# The orgstar+ for Mac price in the live account, pri_…
8# The orgstar+ (Mac) price, pri_…
9PRICE_ID = "pri_REPLACE_ME" 13PRICE_ID = "pri_REPLACE_ME"
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"