packaging/license-issuer/worker.test.mjs

58f3b73e8ff337e5a15111fbb32c0d57cf2346da
orgstar/packaging/license-issuer/worker.test.mjs history · blame · raw

137 lines · 6667 bytes

9 symbols in this file
  1// node --test packaging/license-issuer
  2import assert from "node:assert/strict";
  3import { generateKeyPairSync } from "node:crypto";
  4import { test } from "node:test";
  5import worker, { entitlement, sign, verify } from "./worker.js";
  6
  7const pem = generateKeyPairSync("ed25519").privateKey.export({ type: "pkcs8", format: "pem" });
  8const env = {
  9  SPONSORABLE: "maintainer",
 10  LIFETIME_DOLLARS: "60",
 11  MONTHLY_DOLLARS: "5",
 12  RENEW_DAYS: "40",
 13  GITHUB_CLIENT_ID: "client",
 14  GITHUB_CLIENT_SECRET: "secret",
 15  GITHUB_TOKEN: "maintainer-token",
 16  LICENSE_PRIVATE_KEY: pem,
 17};
 18const config = { lifetime: 60, monthly: 5 };
 19
 20/// Replaces fetch with `respond(url, init)` for the length of `body`.
 21async function withFetch(respond, body) {
 22  const original = globalThis.fetch;
 23  globalThis.fetch = async (url, init) => respond(String(url), init);
 24  try {
 25    return await body();
 26  } finally {
 27    globalThis.fetch = original;
 28  }
 29}
 30
 31const json = (data) => new Response(JSON.stringify(data), { headers: { "content-type": "application/json" } });
 32const sponsorship = (dollars, { oneTime = false, active = true } = {}) => ({
 33  isActive: active,
 34  createdAt: "2026-11-01T12:00:00Z",
 35  tier: { monthlyPriceInDollars: dollars, isOneTime: oneTime },
 36});
 37
 38test("keys verify and tampered keys don't", async () => {
 39  const key = await sign({ e: "octo", t: "github:U_1", i: 1 }, pem);
 40  assert.deepEqual(await verify(key, pem), { e: "octo", t: "github:U_1", i: 1 });
 41  const other = generateKeyPairSync("ed25519").privateKey.export({ type: "pkcs8", format: "pem" });
 42  assert.equal(await verify(await sign({ e: "octo", t: "github:U_1", i: 1 }, other), pem), null);
 43  assert.equal(await verify("ORGSTAR1-abc", pem), null);
 44});
 45
 46test("one-time $60 is lifetime, active monthly $5 is monthly, anything else is nothing", () => {
 47  assert.equal(entitlement(sponsorship(60, { oneTime: true, active: false }), config), "lifetime");
 48  assert.equal(entitlement(sponsorship(100, { oneTime: true }), config), "lifetime");
 49  assert.equal(entitlement(sponsorship(40, { oneTime: true }), config), null);
 50  assert.equal(entitlement(sponsorship(5), config), "monthly");
 51  assert.equal(entitlement(sponsorship(5, { active: false }), config), null);
 52  assert.equal(entitlement(sponsorship(2), config), null);
 53  assert.equal(entitlement(null, config), null);
 54});
 55
 56test("/license without a code redirects to GitHub with a state cookie", async () => {
 57  const response = await worker.fetch(new Request("https://krz.sh/apps/orgstar/license"), env);
 58  assert.equal(response.status, 302);
 59  const location = new URL(response.headers.get("location"));
 60  assert.equal(location.origin + location.pathname, "https://github.com/login/oauth/authorize");
 61  assert.equal(location.searchParams.get("redirect_uri"), "https://krz.sh/apps/orgstar/license");
 62  assert.match(response.headers.get("set-cookie"), new RegExp(`orgstar_state=${location.searchParams.get("state")};`));
 63});
 64
 65/// The callback, with GitHub answering `sponsor` for the signed-in visitor.
 66async function callback(sponsor, { state = "abc", cookie = "abc" } = {}) {
 67  return withFetch(
 68    (url) => url.includes("access_token")
 69      ? json({ access_token: "visitor-token" })
 70      : json({ data: { viewer: { id: "U_1", login: "octo" }, owner: { sponsorshipForViewerAsSponsor: sponsor } } }),
 71    () => worker.fetch(
 72      new Request(`https://krz.sh/apps/orgstar/license?code=c&state=${state}`, { headers: { cookie: `orgstar_state=${cookie}` } }),
 73      env,
 74    ),
 75  );
 76}
 77
 78const keyIn = async (response) => /<pre>([^<]+)<\/pre>/.exec(await response.text())?.[1];
 79
 80test("a one-time sponsor gets the same lifetime key each time", async () => {
 81  const first = await keyIn(await callback(sponsorship(60, { oneTime: true, active: false })));
 82  const second = await keyIn(await callback(sponsorship(60, { oneTime: true, active: false })));
 83  assert.equal(first, second);
 84  assert.deepEqual(await verify(first, pem), { e: "octo", t: "github:U_1", i: Date.parse("2026-11-01T12:00:00Z") / 1000 });
 85});
 86
 87test("a monthly sponsor gets a key that expires", async () => {
 88  const payload = await verify(await keyIn(await callback(sponsorship(5))), pem);
 89  assert.equal(payload.x - payload.i, 40 * 86400);
 90});
 91
 92test("a visitor who isn't sponsoring enough gets no key", async () => {
 93  const response = await callback(sponsorship(1));
 94  assert.equal(response.status, 403);
 95  assert.equal(await keyIn(response), undefined);
 96});
 97
 98test("a callback whose state doesn't match the cookie is refused", async () => {
 99  assert.equal((await callback(sponsorship(5), { cookie: "other" })).status, 400);
100});
101
102/// …/renew with `key`, GitHub listing the maintainer's sponsors in `pages`, with `sponsor` as
103/// U_1's sponsorship on the last page.
104async function renewal(key, sponsor, pages = 1) {
105  const asked = [];
106  const response = await withFetch(
107    (url, init) => {
108      const { variables } = JSON.parse(init.body);
109      asked.push(variables);
110      const page = asked.length;
111      const nodes = [{ ...sponsorship(5), sponsorEntity: { id: `U_other${page}`, login: "someone" } }];
112      if (page === pages && sponsor) nodes.push({ ...sponsor, sponsorEntity: { id: "U_1", login: "octo-renamed" } });
113      const pageInfo = { hasNextPage: page < pages, endCursor: `cursor${page}` };
114      return json({ data: { owner: { sponsorshipsAsMaintainer: { nodes, pageInfo } } } });
115    },
116    () => worker.fetch(new Request("https://krz.sh/apps/orgstar/renew", { method: "POST", body: key }), env),
117  );
118  return { response, asked };
119}
120
121test("renewal extends a monthly key while the sponsorship is active", async () => {
122  const old = await sign({ e: "octo", t: "github:U_1", i: 1, x: 2 }, pem);
123  const { response, asked } = await renewal(old, sponsorship(5), 2);
124  assert.equal(response.status, 200);
125  assert.deepEqual(asked, [{ login: "maintainer", after: null }, { login: "maintainer", after: "cursor1" }]);
126  const fresh = await verify((await response.text()).trim(), pem);
127  assert.equal(fresh.e, "octo-renamed");
128  assert.ok(fresh.x > Date.now() / 1000 + 39 * 86400);
129});
130
131test("renewal refuses ended sponsorships, lifetime keys and forged keys", async () => {
132  const monthly = await sign({ e: "octo", t: "github:U_1", i: 1, x: 2 }, pem);
133  assert.equal((await renewal(monthly, null)).response.status, 403);
134  assert.equal((await renewal(await sign({ e: "octo", t: "github:U_1", i: 1 }, pem), sponsorship(5))).response.status, 400);
135  const other = generateKeyPairSync("ed25519").privateKey.export({ type: "pkcs8", format: "pem" });
136  assert.equal((await renewal(await sign({ e: "octo", t: "github:U_1", i: 1, x: 2 }, other), sponsorship(5))).response.status, 400);
137});