packaging/license-issuer/worker.js
261 lines · 12014 bytes
1// Issues orgstar+ for Mac license keys to GitHub sponsors. Paths are matched by their last
2// segment, so the Worker answers under any route: krz.sh/apps/orgstar/buy, or /buy under
3// `wrangler dev`.
4//
5// GET …/buy shows what orgstar+ includes and the two sponsorships that come with a key, linking to
6// github.com/sponsors/SPONSORABLE, and to …/license for a sponsor's key.
7//
8// GET …/license signs in with GitHub (OAuth, state in a cookie) and asks GitHub for the visitor's
9// sponsorship of SPONSORABLE:
10// - one-time, LIFETIME_DOLLARS or more: a key that doesn't expire, the same one each time;
11// - monthly and active, MONTHLY_DOLLARS or more: a key that expires RENEW_DAYS after it is issued.
12//
13// POST …/renew with a monthly key as the body returns a fresh one while that sponsorship is
14// still active (403 when it isn't). orgstar renews monthly keys in the background.
15//
16// A key is `ORGSTAR1-<payload>.<signature>`: base64url JSON {"e": GitHub login, "t": "github:" +
17// the account's node ID, "i": issued, "x": expires (monthly keys only), seconds}, signed with
18// Ed25519. The app checks it offline (Sources/OrgApp/LicenseKey.swift). Nothing is stored.
19//
20// Vars (wrangler.toml): SPONSORABLE, LIFETIME_DOLLARS, MONTHLY_DOLLARS, RENEW_DAYS,
21// GITHUB_CLIENT_ID. Secrets (`wrangler secret put NAME`; locally .dev.vars, see
22// .dev.vars.example): GITHUB_CLIENT_SECRET, GITHUB_TOKEN (SPONSORABLE's token, for renewals),
23// LICENSE_PRIVATE_KEY (PKCS#8 PEM, from keygen.sh).
24
25const FEATURES = [
26 "Run and tangle source blocks",
27 "PDF, Word and other export, and publishing",
28 "Encrypted entries",
29 "Org-roam and Denote notes, daily notes and backlinks",
30 "Widgets",
31 "Calendar and Reminders",
32 "Shortcuts actions",
33];
34
35const STATE_COOKIE = "orgstar_state";
36
37/// Reads the settings and throws when one is missing.
38function settings(env, ...secrets) {
39 for (const name of ["SPONSORABLE", ...secrets])
40 if (!env[name]) throw new Error(`${name} is not set`);
41 const number = (name) => {
42 const value = Number(env[name]);
43 if (!(value > 0)) throw new Error(`${name} must be a positive number, not ${JSON.stringify(env[name])}`);
44 return value;
45 };
46 return {
47 sponsorable: env.SPONSORABLE,
48 lifetime: number("LIFETIME_DOLLARS"),
49 monthly: number("MONTHLY_DOLLARS"),
50 renewDays: number("RENEW_DAYS"),
51 };
52}
53
54export default {
55 async fetch(request, env) {
56 const url = new URL(request.url);
57 if (url.pathname.endsWith("/buy")) return buy(url, env);
58 if (url.pathname.endsWith("/license")) return license(request, url, env);
59 if (url.pathname.endsWith("/renew") && request.method === "POST") return renew(request, env);
60 return new Response("Not found", { status: 404 });
61 },
62};
63
64function buy(url, env) {
65 const { sponsorable, lifetime, monthly } = settings(env);
66 const features = FEATURES.map((feature) => `<li>${feature}</li>`).join("");
67 return page(
68 `<p>orgstar+ for Mac comes with sponsoring orgstar on GitHub. Editing, the agenda, capture, ` +
69 `clocking, tables and search stay free.</p><ul>${features}</ul>` +
70 `<ul class="tiers"><li><b>$${lifetime} once</b>: a license key that doesn't expire.</li>` +
71 `<li><b>$${monthly} a month</b>: a key that orgstar renews while you sponsor.</li></ul>` +
72 `<p><a class="button" href="https://github.com/sponsors/${sponsorable}">Sponsor on GitHub</a></p>` +
73 `<p>Then <a href="${new URL("license", url)}">sign in with GitHub to get your key</a>.</p>` +
74 `<p class="note">Payment is through GitHub Sponsors and needs a GitHub account.</p>`,
75 200,
76 "orgstar+ for Mac",
77 );
78}
79
80async function license(request, url, env) {
81 const config = settings(env, "GITHUB_CLIENT_ID", "GITHUB_CLIENT_SECRET", "LICENSE_PRIVATE_KEY");
82 const self = new URL(url.pathname, url);
83 const code = url.searchParams.get("code");
84 if (!code) {
85 const state = [...crypto.getRandomValues(new Uint8Array(16))].map((b) => b.toString(16).padStart(2, "0")).join("");
86 const authorize = new URL("https://github.com/login/oauth/authorize");
87 authorize.searchParams.set("client_id", env.GITHUB_CLIENT_ID);
88 authorize.searchParams.set("redirect_uri", self.href);
89 authorize.searchParams.set("scope", "read:user");
90 authorize.searchParams.set("state", state);
91 authorize.searchParams.set("allow_signup", "true");
92 return new Response(null, {
93 status: 302,
94 headers: {
95 location: authorize.href,
96 "set-cookie": `${STATE_COOKIE}=${state}; Path=${url.pathname}; Max-Age=600; HttpOnly; Secure; SameSite=Lax`,
97 },
98 });
99 }
100
101 const cookie = (request.headers.get("cookie") ?? "").split(/;\s*/).find((c) => c.startsWith(STATE_COOKIE + "="));
102 if (!cookie || cookie.slice(STATE_COOKIE.length + 1) !== url.searchParams.get("state"))
103 return page(`The sign-in expired. <a href="${self}">Sign in again</a>.`, 400);
104
105 const exchange = await fetch("https://github.com/login/oauth/access_token", {
106 method: "POST",
107 headers: { accept: "application/json", "content-type": "application/json" },
108 body: JSON.stringify({ client_id: env.GITHUB_CLIENT_ID, client_secret: env.GITHUB_CLIENT_SECRET, code, redirect_uri: self.href }),
109 });
110 const token = exchange.ok ? (await exchange.json()).access_token : null;
111 if (!token) return page(`GitHub didn't complete the sign-in. <a href="${self}">Try again</a>.`, 502);
112
113 const data = await graphql(
114 token,
115 `query($login: String!) {
116 viewer { id login }
117 user(login: $login) {
118 sponsorshipForViewerAsSponsor(activeOnly: false) {
119 isActive createdAt tier { monthlyPriceInDollars isOneTime }
120 }
121 }
122 }`,
123 { login: config.sponsorable },
124 );
125 if (!data) return page("GitHub can't be reached right now. Try again in a minute.", 502);
126
127 const { viewer } = data;
128 const kind = entitlement(data.user?.sponsorshipForViewerAsSponsor, config);
129 const sponsor = `https://github.com/sponsors/${config.sponsorable}`;
130 const clear = { "set-cookie": `${STATE_COOKIE}=; Path=${url.pathname}; Max-Age=0; HttpOnly; Secure; SameSite=Lax` };
131 if (!kind)
132 return page(
133 `${escape(viewer.login)} isn't sponsoring at a level that includes orgstar+: $${config.lifetime} once, ` +
134 `or $${config.monthly} or more a month. <a href="${sponsor}">Sponsor on GitHub</a>, then come back to this page.`,
135 403,
136 "orgstar+",
137 clear,
138 );
139
140 const t = "github:" + viewer.id;
141 const payload = kind === "lifetime"
142 ? { e: viewer.login, t, i: seconds(data.user.sponsorshipForViewerAsSponsor.createdAt) }
143 : monthlyPayload(viewer.login, t, config.renewDays);
144 const key = await sign(payload, env.LICENSE_PRIVATE_KEY);
145 const note = kind === "lifetime"
146 ? "It doesn't expire, and this page shows the same key whenever you sign in again."
147 : `orgstar renews it while your monthly sponsorship continues. If you stop, orgstar+ ends when the key expires.`;
148 return page(
149 `<p>Your orgstar+ license key:</p><pre>${key}</pre>` +
150 `<p>In orgstar, open Settings ▸ orgstar+, paste the key and choose Activate. ${note}</p>`,
151 200,
152 "orgstar+",
153 clear,
154 );
155}
156
157/// "lifetime", "monthly" or null for a sponsorship from GitHub's API.
158export function entitlement(sponsorship, { lifetime, monthly }) {
159 const dollars = sponsorship?.tier?.monthlyPriceInDollars ?? 0;
160 if (!sponsorship) return null;
161 if (sponsorship.tier?.isOneTime) return dollars >= lifetime ? "lifetime" : null;
162 return sponsorship.isActive && dollars >= monthly ? "monthly" : null;
163}
164
165function monthlyPayload(login, t, renewDays) {
166 const now = Math.floor(Date.now() / 1000);
167 return { e: login, t, i: now, x: now + renewDays * 86400 };
168}
169
170async function renew(request, env) {
171 const config = settings(env, "GITHUB_TOKEN", "LICENSE_PRIVATE_KEY");
172 const payload = await verify((await request.text()).replace(/\s/g, ""), env.LICENSE_PRIVATE_KEY);
173 if (!payload?.x || !payload.t?.startsWith("github:")) return text("Not a monthly orgstar+ key.", 400);
174
175 const data = await graphql(
176 env.GITHUB_TOKEN,
177 `query($id: ID!) {
178 node(id: $id) {
179 ... on User { login sponsorshipForViewerAsSponsorable(activeOnly: true) { isActive tier { monthlyPriceInDollars isOneTime } } }
180 ... on Organization { login sponsorshipForViewerAsSponsorable(activeOnly: true) { isActive tier { monthlyPriceInDollars isOneTime } } }
181 }
182 }`,
183 { id: payload.t.slice("github:".length) },
184 );
185 if (!data) return text("GitHub can't be reached right now.", 502);
186 const node = data.node;
187 if (entitlement(node?.sponsorshipForViewerAsSponsorable, config) !== "monthly")
188 return text("The monthly sponsorship has ended.", 403);
189 return text(await sign(monthlyPayload(node.login, payload.t, config.renewDays), env.LICENSE_PRIVATE_KEY), 200);
190}
191
192async function graphql(token, query, variables) {
193 const response = await fetch("https://api.github.com/graphql", {
194 method: "POST",
195 headers: { authorization: `Bearer ${token}`, "content-type": "application/json", "user-agent": "orgstar-license" },
196 body: JSON.stringify({ query, variables }),
197 });
198 if (!response.ok) return null;
199 const body = await response.json();
200 return body.data ?? null;
201}
202
203function seconds(iso) {
204 return Math.floor(Date.parse(iso) / 1000);
205}
206
207async function keys(pem) {
208 const der = Uint8Array.from(atob(pem.replace(/-----[^-]+-----|\s|\\n/g, "")), (c) => c.charCodeAt(0));
209 const privateKey = await crypto.subtle.importKey("pkcs8", der, { name: "Ed25519" }, true, ["sign"]);
210 const { x } = await crypto.subtle.exportKey("jwk", privateKey);
211 const publicKey = await crypto.subtle.importKey("jwk", { kty: "OKP", crv: "Ed25519", x }, { name: "Ed25519" }, false, ["verify"]);
212 return { privateKey, publicKey };
213}
214
215export async function sign(payload, pem) {
216 const { privateKey } = await keys(pem);
217 const body = new TextEncoder().encode(JSON.stringify(payload));
218 const signature = new Uint8Array(await crypto.subtle.sign({ name: "Ed25519" }, privateKey, body));
219 return `ORGSTAR1-${base64url(body)}.${base64url(signature)}`;
220}
221
222/// The payload of a key this issuer signed, or null.
223export async function verify(key, pem) {
224 const match = /^ORGSTAR1-([\w-]+)\.([\w-]+)$/.exec(key);
225 if (!match) return null;
226 const [body, signature] = [unbase64url(match[1]), unbase64url(match[2])];
227 const { publicKey } = await keys(pem);
228 if (!(await crypto.subtle.verify({ name: "Ed25519" }, publicKey, signature, body))) return null;
229 try {
230 return JSON.parse(new TextDecoder().decode(body));
231 } catch {
232 return null;
233 }
234}
235
236function base64url(bytes) {
237 return btoa(String.fromCharCode(...bytes)).replace(/\+/g, "-").replace(/\//g, "_").replace(/=+$/, "");
238}
239
240function unbase64url(text) {
241 const padded = text.replace(/-/g, "+").replace(/_/g, "/") + "=".repeat((4 - (text.length % 4)) % 4);
242 return Uint8Array.from(atob(padded), (c) => c.charCodeAt(0));
243}
244
245function escape(text) {
246 return String(text).replace(/[&<>"]/g, (c) => ({ "&": "&", "<": "<", ">": ">", '"': """ })[c]);
247}
248
249function text(body, status) {
250 return new Response(body + "\n", { status, headers: { "content-type": "text/plain; charset=utf-8" } });
251}
252
253function page(body, status, heading = "orgstar+", headers = {}) {
254 const html = `<!doctype html><meta charset="utf-8"><meta name="viewport" content="width=device-width">` +
255 `<title>${heading}</title><style>body{font:16px/1.5 system-ui;max-width:40rem;margin:3rem auto;padding:0 1rem}` +
256 `pre{white-space:pre-wrap;word-break:break-all;background:#f4f4f4;padding:1rem;border-radius:6px}` +
257 `.tiers{list-style:none;padding:0}.note{color:#666;font-size:.9rem}` +
258 `.button{display:inline-block;font-weight:600;padding:.7rem 1.4rem;border-radius:8px;background:#d4a017;color:#fff;text-decoration:none}</style>` +
259 `<h1>${heading}</h1>${body.startsWith("<") ? body : `<p>${body}</p>`}`;
260 return new Response(html, { status, headers: { "content-type": "text/html; charset=utf-8", ...headers } });
261}