iterate.com / kernel

git clone https://git.iterate.com/repos/kernel

deploy: the subscription follows the agreed terms, a lost answer is reconciled, a failed revocation is said

The reviewer's read of 54f58aa, pull #22:

1. The price shown was a snapshot. The terms are now read again right before
   each request, and terms that changed after the yes make no subscription.
   A price in Cloudflare's answer that differs from the agreed one is said,
   with where to cancel. Cloudflare's API has no quote, so a change in the
   moment between that read and the request is not caught.
2. The end of the billing access is asked for up to three times, and a
   failure is said. An OAuth answer that is not ok and names no error is now
   an error: a refused revocation read as done before.
3. Each product's subscription ends in an outcome of its own, so one failure
   loses no other's result. An answer that did not arrive (a 5xx, a dropped
   connection) is 'lost', never 'nothing bought': the account is read for up
   to two minutes, and the person is sent to the subscriptions page before
   any purchase by hand.

Card: tasks/offer-workers-paid-and-r2-activation-in-the-deploy-cli.md
Via: /agents/claude/installer-cloudflare-card-prompt-mwynk7y7-d3de92
Session: claude 3eb581c8-1b51-4686-8d1d-b642d0822a42 on beelink
Co-Authored-By: Claude Fable 5.2 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_014UJeUkb5YT4HuZzZEVabHj

Jonas Templestein, 2026-11-27 09:28 UTC · 8d890b7f5b577b427a7d4ec7336b1eebd48a2425 · parent 8fbb2d2

5 files changed

M core/lib/src/cli/README.md
@@ -159,6 +159,16 @@
      (`BILLING_SCOPE`, `briefAccess`): that access is in no file, makes the subscriptions
      (`POST /accounts/<id>/subscriptions`) and is ended at Cloudflare at once. No sign-in that is
      kept ever holds that scope.
+   - **What the request is bound to.** Cloudflare's API takes the plan's name and no price, and
+     has no quote to agree to. So right before each request the command reads the product again
+     (one that came on meanwhile is not subscribed to twice) and the plan's terms again: terms
+     that changed after the yes make no subscription. A price in Cloudflare's answer that is not
+     the price agreed to is said, with where to cancel. A price that changes in the moment
+     between that read and the request is not caught.
+   - **An answer that does not arrive** (a 5xx, a dropped connection) may still be a subscription:
+     the command reads the account for up to two minutes, and sends the person to the account's
+     subscriptions before any purchase by hand. A revocation that Cloudflare does not confirm
+     after three tries is said: the access then ends by itself within the hour.
    - **The way by hand stays.** With a no, with terms that the command could not read for
      certain, with an API token or a kept sign-in, with nobody at the terminal, or when
      Cloudflare refuses the approval or the subscription, the command opens the product's page
M core/lib/src/cli/cloudflare-access.test.ts
@@ -238,6 +238,7 @@
   expect(CARD_SCOPE).not.toBe(BILLING_SCOPE);
 
   const calls: { path: string; form: Record<string, string> }[] = [];
+  let revokeFails = false;
   const cloudflareSays = (granted: string) =>
     vi.stubGlobal("fetch", async (url: string | URL, init?: RequestInit) => {
       const path = new URL(String(url)).pathname;
@@ -254,6 +255,7 @@
         : path.endsWith("/token")
           ? { access_token: "billing-token", expires_in: 3600, scope: granted }
           : {};
+      if (path.endsWith("/revoke") && revokeFails) return new Response("{}", { status: 400 });
       return new Response(JSON.stringify(answer), { headers: { "content-type": "application/json" } });
     });
   const revoked = () => calls.filter((call) => call.path.endsWith("/revoke")).map((call) => call.form.token);
@@ -292,7 +294,33 @@
     ).toEqual({ lacks: [BILLING_SCOPE] });
     expect(acted).toBe(false);
     expect(revoked()).toEqual(["billing-token"]);
+
+    // a revocation that Cloudflare refuses: asked for three times, and said, never silent
+    calls.length = 0;
+    revokeFails = true;
+    cloudflareSays(BILLING_SCOPE);
+    const waits: number[] = [];
+    const notEnded = await briefAccess(
+      [BILLING_SCOPE],
+      () => {},
+      async () => "acted",
+      async (ms) => void waits.push(ms),
+    );
+    expect(notEnded).toEqual({ lacks: [], done: "acted", notEnded: "HTTP 400" });
+    expect(revoked()).toEqual(["billing-token", "billing-token", "billing-token"]);
+    expect(waits).toEqual([1000, 2000]);
+    await expect(
+      briefAccess(
+        [BILLING_SCOPE],
+        () => {},
+        async () => {
+          throw new Error("The act failed.");
+        },
+        async () => {},
+      ),
+    ).rejects.toThrow("The act failed. The access for it was not ended at Cloudflare (HTTP 400)");
   } finally {
     vi.unstubAllGlobals();
   }
-});
+  // each sign-in here waits one second for the device flow's first poll
+}, 20_000);
M core/lib/src/cli/cloudflare-access.ts
@@ -271,7 +271,9 @@
     options,
   );
   const said = parsed(OAuthAnswer, await answer.text());
-  if (said) return said;
+  // an answer that is not ok is an error also when its body names none: a refused revocation
+  // must never read as done
+  if (said && (answer.ok || said.error)) return said;
   if (answer.ok) return {};
   if (answer.status === 403) {
     const mitigated = answer.headers.get("cf-mitigated");
@@ -424,20 +426,37 @@
 /** A SIGN-IN FOR ONE ACT, KEPT NOWHERE: the device flow with `scopes` alone, then `act` with its
  *  token, then the token's end at Cloudflare, whatever `act` did. The token is in no file and in
  *  no other call of the run. A sign-in that did not grant every scope does not act: `lacks` names
- *  what is missing. It throws what the sign-in throws (refused, or nobody approved in time). */
+ *  what is missing. THE END IS ASKED FOR UP TO THREE TIMES, AND A FAILURE IS SAID: `notEnded` is
+ *  Cloudflare's error when the token may still work (it then ends by itself within the hour),
+ *  and an `act` that throws carries the same words. It throws what the sign-in throws (refused,
+ *  or nobody approved in time): nothing was acted on then. */
 export async function briefAccess<T>(
   scopes: readonly string[],
   show: Parameters<typeof deviceSignIn>[1],
   act: (token: string) => Promise<T>,
-): Promise<{ lacks: string[]; done?: T }> {
+  pause: (ms: number) => Promise<unknown> = sleep,
+): Promise<{ lacks: string[]; done?: T; notEnded?: string }> {
   const answer = await deviceSignIn(scopes, show);
-  try {
-    const lacks = scopesLacking(scopes, answer.scope);
-    return lacks.length > 0 ? { lacks } : { lacks, done: await act(answer.access_token) };
-  } finally {
+  const end = async () => {
     await revoke(answer.refresh_token);
-    await revoke(answer.access_token);
+    for (let attempt = 1; ; attempt++) {
+      const problem = await revoke(answer.access_token);
+      if (!problem || attempt === 3) return problem;
+      await pause(attempt * 1000);
+    }
+  };
+  const lacks = scopesLacking(scopes, answer.scope);
+  let done: T | undefined;
+  try {
+    if (lacks.length === 0) done = await act(answer.access_token);
+  } catch (error) {
+    const notEnded = await end();
+    if (notEnded && error instanceof Error)
+      error.message += ` The access for it was not ended at Cloudflare (${notEnded}): it ends by itself within the hour.`;
+    throw error;
   }
+  const notEnded = await end();
+  return { lacks, ...(lacks.length === 0 ? { done } : {}), ...(notEnded ? { notEnded } : {}) };
 }
 
 // ---------------------------------------------------------------------------------------------
M core/lib/src/cli/deploy.test.ts
@@ -8,6 +8,7 @@
 import {
   activationOffer,
   activationOutcomeOf,
+  activationReport,
   alternativesOf,
   assertSupportedNodeVersion,
   boundaryCheck,
@@ -22,6 +23,7 @@
   deployConfigOf,
   patternsRefusalOf,
   planTermsOf,
+  sameTerms,
   PRODUCTS,
   subscriptionBodyOf,
   deployedMind,
@@ -2377,4 +2379,69 @@
   expect(
     activationOutcomeOf({ status: 400, result: undefined, total: 0, error: "no payment method" }),
   ).toEqual({ on: false, why: "400: no payment method" });
+});
+
+test("the request follows the terms that the person agreed to: terms that changed after the yes make no subscription", () => {
+  const agreed = planTermsOf("workers_paid", catalog(workersPaidPlan))!;
+  expect(sameTerms(agreed, planTermsOf("workers_paid", catalog(workersPaidPlan)))).toBe(true);
+  const dearer = structuredClone(workersPaidPlan);
+  dearer.components[0]!.tiers[0]!.price = 6;
+  expect(sameTerms(agreed, planTermsOf("workers_paid", catalog(dearer)))).toBe(false);
+  expect(sameTerms(agreed, undefined)).toBe(false);
+});
+
+test("after the subscriptions: one product's failure loses no other's result, and a lost answer is never called nothing bought", () => {
+  const paid = planTermsOf("workers_paid", catalog(workersPaidPlan))!;
+  const r2 = planTermsOf("r2_paid", catalog(r2Plan))!;
+  // an answer with a 5xx, like a request that threw, is lost: Cloudflare may have made it
+  expect(activationOutcomeOf({ status: 502, result: undefined, total: 0, error: "bad gateway" })).toEqual({
+    lost: "502: bad gateway",
+  });
+  expect(activationOutcomeOf({ status: 200, result: { price: 5 }, total: 0, error: "" })).toEqual({
+    on: true,
+    charged: 5,
+  });
+
+  // Workers Paid was made, the answer for R2 was lost and R2 is still off
+  const report = activationReport({
+    account: "acc1",
+    outcomes: [
+      { product: "Workers Paid", agreed: paid, outcome: { on: true, charged: 5 }, onNow: false },
+      { product: "R2", agreed: r2, outcome: { lost: "fetch failed" }, onNow: false },
+    ],
+  });
+  expect(report.byHand).toEqual(["R2"]);
+  expect(report.lines[0]).toEqual({ kind: "success", text: "Workers Paid is on." });
+  expect(report.lines[1]!.kind).toBe("warn");
+  expect(report.lines[1]!.text).toContain("may have made the subscription");
+  expect(report.lines[1]!.text).toContain("https://dash.cloudflare.com/acc1/billing/subscriptions");
+  expect(report.lines[1]!.text).not.toContain("Nothing was");
+
+  // a lost answer whose product the account then shows on: it is on, and nothing is bought by hand
+  expect(
+    activationReport({
+      account: "acc1",
+      outcomes: [{ product: "R2", agreed: r2, outcome: { lost: "fetch failed" }, onNow: true }],
+    }),
+  ).toEqual({ lines: [{ kind: "success", text: "R2 is on." }], byHand: [] });
+
+  // a refusal: nothing was bought for it, and the page by hand follows
+  const refused = activationReport({
+    account: "acc1",
+    outcomes: [
+      { product: "Workers Paid", agreed: paid, outcome: { on: false, why: "403: no" }, onNow: false },
+    ],
+  });
+  expect(refused.byHand).toEqual(["Workers Paid"]);
+  expect(refused.lines[0]!.text).toContain("Nothing was bought for it");
+
+  // a price in Cloudflare's answer that is not the price agreed to is said, with where to cancel
+  const other = activationReport({
+    account: "acc1",
+    outcomes: [
+      { product: "Workers Paid", agreed: paid, outcome: { on: true, charged: 6 }, onNow: false },
+    ],
+  });
+  expect(other.byHand).toEqual([]);
+  expect(other.lines[1]!.text).toContain("names $6 a month for Workers Paid, not the $5");
 });
M core/lib/src/cli/deploy.ts

Not shown: the change is larger than this page shows. A clone has it.