packaging/license-issuer/worker.js
285 lines · 12962 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 (an owner of SPONSORABLE, 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 owner: repositoryOwner(login: $login) {
118 ... on Sponsorable {
119 sponsorshipForViewerAsSponsor(activeOnly: false) {
120 isActive createdAt tier { monthlyPriceInDollars isOneTime }
121 }
122 }
123 }
124 }`,
125 { login: config.sponsorable },
126 );
127 if (!data) return page("GitHub can't be reached right now. Try again in a minute.", 502);
128
129 const { viewer } = data;
130 const sponsorship = data.owner?.sponsorshipForViewerAsSponsor;
131 const kind = entitlement(sponsorship, config);
132 const sponsor = `https://github.com/sponsors/${config.sponsorable}`;
133 const clear = { "set-cookie": `${STATE_COOKIE}=; Path=${url.pathname}; Max-Age=0; HttpOnly; Secure; SameSite=Lax` };
134 if (!kind)
135 return page(
136 `${escape(viewer.login)} isn't sponsoring at a level that includes orgstar+: $${config.lifetime} once, ` +
137 `or $${config.monthly} or more a month. <a href="${sponsor}">Sponsor on GitHub</a>, then come back to this page.`,
138 403,
139 "orgstar+",
140 clear,
141 );
142
143 const t = "github:" + viewer.id;
144 const payload = kind === "lifetime"
145 ? { e: viewer.login, t, i: seconds(sponsorship.createdAt) }
146 : monthlyPayload(viewer.login, t, config.renewDays);
147 const key = await sign(payload, env.LICENSE_PRIVATE_KEY);
148 const note = kind === "lifetime"
149 ? "It doesn't expire, and this page shows the same key whenever you sign in again."
150 : `orgstar renews it while your monthly sponsorship continues. If you stop, orgstar+ ends when the key expires.`;
151 return page(
152 `<p>Your orgstar+ license key:</p><pre>${key}</pre>` +
153 `<p>In orgstar, open Settings ▸ orgstar+, paste the key and choose Activate. ${note}</p>`,
154 200,
155 "orgstar+",
156 clear,
157 );
158}
159
160/// "lifetime", "monthly" or null for a sponsorship from GitHub's API.
161export function entitlement(sponsorship, { lifetime, monthly }) {
162 const dollars = sponsorship?.tier?.monthlyPriceInDollars ?? 0;
163 if (!sponsorship) return null;
164 if (sponsorship.tier?.isOneTime) return dollars >= lifetime ? "lifetime" : null;
165 return sponsorship.isActive && dollars >= monthly ? "monthly" : null;
166}
167
168function monthlyPayload(login, t, renewDays) {
169 const now = Math.floor(Date.now() / 1000);
170 return { e: login, t, i: now, x: now + renewDays * 86400 };
171}
172
173async function renew(request, env) {
174 const config = settings(env, "GITHUB_TOKEN", "LICENSE_PRIVATE_KEY");
175 const payload = await verify((await request.text()).replace(/\s/g, ""), env.LICENSE_PRIVATE_KEY);
176 if (!payload?.x || !payload.t?.startsWith("github:")) return text("Not a monthly orgstar+ key.", 400);
177
178 const found = await activeSponsorship(env.GITHUB_TOKEN, config.sponsorable, payload.t.slice("github:".length));
179 if (found === undefined) return text("GitHub can't be reached right now.", 502);
180 if (entitlement(found, config) !== "monthly") return text("The monthly sponsorship has ended.", 403);
181 return text(await sign(monthlyPayload(found.sponsorEntity.login, payload.t, config.renewDays), env.LICENSE_PRIVATE_KEY), 200);
182}
183
184/// The active sponsorship of `sponsorable` by the account with node ID `id`, from the
185/// sponsorable's own list (private ones too, so `token` belongs to it or an owner of it); null
186/// when there is none, undefined when GitHub can't be reached.
187async function activeSponsorship(token, sponsorable, id) {
188 let after = null;
189 for (;;) {
190 const data = await graphql(
191 token,
192 `query($login: String!, $after: String) {
193 owner: repositoryOwner(login: $login) {
194 ... on Sponsorable {
195 sponsorshipsAsMaintainer(first: 100, after: $after, activeOnly: true, includePrivate: true) {
196 nodes {
197 isActive tier { monthlyPriceInDollars isOneTime }
198 sponsorEntity { ... on User { id login } ... on Organization { id login } }
199 }
200 pageInfo { hasNextPage endCursor }
201 }
202 }
203 }
204 }`,
205 { login: sponsorable, after },
206 );
207 const list = data?.owner?.sponsorshipsAsMaintainer;
208 if (!list) return undefined;
209 const match = list.nodes.find((node) => node.sponsorEntity?.id === id);
210 if (match) return match;
211 if (!list.pageInfo.hasNextPage) return null;
212 after = list.pageInfo.endCursor;
213 }
214}
215
216async function graphql(token, query, variables) {
217 const response = await fetch("https://api.github.com/graphql", {
218 method: "POST",
219 headers: { authorization: `Bearer ${token}`, "content-type": "application/json", "user-agent": "orgstar-license" },
220 body: JSON.stringify({ query, variables }),
221 });
222 if (!response.ok) return null;
223 const body = await response.json();
224 return body.data ?? null;
225}
226
227function seconds(iso) {
228 return Math.floor(Date.parse(iso) / 1000);
229}
230
231async function keys(pem) {
232 const der = Uint8Array.from(atob(pem.replace(/-----[^-]+-----|\s|\\n/g, "")), (c) => c.charCodeAt(0));
233 const privateKey = await crypto.subtle.importKey("pkcs8", der, { name: "Ed25519" }, true, ["sign"]);
234 const { x } = await crypto.subtle.exportKey("jwk", privateKey);
235 const publicKey = await crypto.subtle.importKey("jwk", { kty: "OKP", crv: "Ed25519", x }, { name: "Ed25519" }, false, ["verify"]);
236 return { privateKey, publicKey };
237}
238
239export async function sign(payload, pem) {
240 const { privateKey } = await keys(pem);
241 const body = new TextEncoder().encode(JSON.stringify(payload));
242 const signature = new Uint8Array(await crypto.subtle.sign({ name: "Ed25519" }, privateKey, body));
243 return `ORGSTAR1-${base64url(body)}.${base64url(signature)}`;
244}
245
246/// The payload of a key this issuer signed, or null.
247export async function verify(key, pem) {
248 const match = /^ORGSTAR1-([\w-]+)\.([\w-]+)$/.exec(key);
249 if (!match) return null;
250 const [body, signature] = [unbase64url(match[1]), unbase64url(match[2])];
251 const { publicKey } = await keys(pem);
252 if (!(await crypto.subtle.verify({ name: "Ed25519" }, publicKey, signature, body))) return null;
253 try {
254 return JSON.parse(new TextDecoder().decode(body));
255 } catch {
256 return null;
257 }
258}
259
260function base64url(bytes) {
261 return btoa(String.fromCharCode(...bytes)).replace(/\+/g, "-").replace(/\//g, "_").replace(/=+$/, "");
262}
263
264function unbase64url(text) {
265 const padded = text.replace(/-/g, "+").replace(/_/g, "/") + "=".repeat((4 - (text.length % 4)) % 4);
266 return Uint8Array.from(atob(padded), (c) => c.charCodeAt(0));
267}
268
269function escape(text) {
270 return String(text).replace(/[&<>"]/g, (c) => ({ "&": "&", "<": "<", ">": ">", '"': """ })[c]);
271}
272
273function text(body, status) {
274 return new Response(body + "\n", { status, headers: { "content-type": "text/plain; charset=utf-8" } });
275}
276
277function page(body, status, heading = "orgstar+", headers = {}) {
278 const html = `<!doctype html><meta charset="utf-8"><meta name="viewport" content="width=device-width">` +
279 `<title>${heading}</title><style>body{font:16px/1.5 system-ui;max-width:40rem;margin:3rem auto;padding:0 1rem}` +
280 `pre{white-space:pre-wrap;word-break:break-all;background:#f4f4f4;padding:1rem;border-radius:6px}` +
281 `.tiers{list-style:none;padding:0}.note{color:#666;font-size:.9rem}` +
282 `.button{display:inline-block;font-weight:600;padding:.7rem 1.4rem;border-radius:8px;background:#d4a017;color:#fff;text-decoration:none}</style>` +
283 `<h1>${heading}</h1>${body.startsWith("<") ? body : `<p>${body}</p>`}`;
284 return new Response(html, { status, headers: { "content-type": "text/html; charset=utf-8", ...headers } });
285}