packaging/license-issuer/worker.js
153 lines · 7959 bytes
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`.
4//
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
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.
14//
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};
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}
49
50export default {
51 async fetch(request, env) {
52 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);
55 return new Response("Not found", { status: 404 });
56 },
57};
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
133export 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"]);
136 const body = new TextEncoder().encode(JSON.stringify(payload));
137 const signature = new Uint8Array(await crypto.subtle.sign({ name: "Ed25519" }, privateKey, body));
138 return `ORGSTAR1-${base64url(body)}.${base64url(signature)}`;
139}
140
141function base64url(bytes) {
142 return btoa(String.fromCharCode(...bytes)).replace(/\+/g, "-").replace(/\//g, "_").replace(/=+$/, "");
143}
144
145function page(body, status, heading = "orgstar+") {
146 const html = `<!doctype html><meta charset="utf-8"><meta name="viewport" content="width=device-width">` +
147 `<title>${heading}</title><style>body{font:16px/1.5 system-ui;max-width:40rem;margin:3rem auto;padding:0 1rem}` +
148 `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>` +
151 `<h1>${heading}</h1>${body.startsWith("<") ? body : `<p>${body}</p>`}`;
152 return new Response(html, { status, headers: { "content-type": "text/html; charset=utf-8" } });
153}