iterate.com / kernel

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

deploy: the command offers to turn Workers Paid and R2 on, after the exact terms and a yes

Jonas, on the board: "it should also be modified to create the workers paid
plan and r2 subscription for user". Cloudflare made this possible on 25 Nov
2026 (changelog "Activate Cloudflare subscriptions from the CLI and MCP").

For each of Workers Paid and R2 that is off, `iterate deploy` reads the rate
plan in Cloudflare's public catalog, shows its name and its fixed monthly fee,
and asks. The default answer is no. After a yes, a second approval at
Cloudflare gives the scope billing:write alone. That access is in no file,
makes the subscriptions and is ended at Cloudflare at once. The one-hour
sign-in and a kept sign-in never ask for the scope.

No offer, and the page by hand as before: a no, terms that are not read for
certain, an account with no payment card, an API token, a kept sign-in, nobody
at the terminal, or a refusal by Cloudflare.

Tested with fixtures only: the catalog's two answers of 27 Nov 2026, the
offer, no offer, a refusal, and the brief access against a faked OAuth server.
Not proven live: that Cloudflare grants billing:write to the cf client alone,
and that it takes the body { rate_plan: { id }, frequency: "monthly" }. No
subscription was made.

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:24 UTC · 54f58aa969f4cc450322feff4ed7aa48608b87cf · parent 71b85ef

5 files changed

M core/lib/src/cli/README.md
@@ -150,7 +150,21 @@
 5. **Workers Paid, R2 and Zero Trust.** It opens the page for each one that is off and waits
    until it is on. Off means Cloudflare refused the read, and the account's line shows its words.
    A read that failed is not a fact: a 429 or a 5xx is read again, and after three the command
-   stops with nothing changed and says to run it again. An owner proves their address through Cloudflare Access, which needs the
+   stops with nothing changed and says to run it again.
+   - **The command offers to turn Workers Paid and R2 on itself**, for a person at the terminal
+     who signed in at Cloudflare's page. For each of the two that is off, it reads the rate plan
+     in Cloudflare's public catalog (`GET /billing/rate_plans/workers_paid`, `…/r2_paid`), shows
+     the plan's name and its fixed monthly fee, and asks. The default answer is no. After a yes,
+     Cloudflare asks once more for an approval, of the scope `billing:write` alone
+     (`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.
+   - **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
+     and waits, as before.
+
+   An owner proves their address through Cloudflare Access, which needs the
    account's Zero Trust organization. When the account has none, the command first sets one up
    through Cloudflare's API, as the script would, with a team name that Cloudflare picks. When
    Cloudflare refuses that because Zero Trust was never turned on, it opens the account's Zero
M core/lib/src/cli/cloudflare-access.test.ts
@@ -1,8 +1,10 @@
 import { existsSync, mkdtempSync, rmSync, writeFileSync } from "node:fs";
 import { tmpdir } from "node:os";
 import { join } from "node:path";
-import { expect, test } from "vitest";
+import { expect, test, vi } from "vitest";
 import {
+  BILLING_SCOPE,
+  briefAccess,
   CARD_SCOPE,
   DEPLOY_SCOPES,
   keptTokenServes,
@@ -228,4 +230,69 @@
   const lacking = { ...before, scopes: DEPLOY_SCOPES.filter((s) => s !== "d1.write").join(" ") };
   expect(keptTokenServes(lacking, DEPLOY_SCOPES, at)).toBe(false);
   expect(keptTokenServes({ ...before, expiresAt: at + 19 * 60_000 }, DEPLOY_SCOPES, at)).toBe(false);
+});
+
+test("the billing access is asked for alone, held in no file, used for the one act and ended at Cloudflare, also when the act throws", async () => {
+  // the scope that can spend is in no list that a kept or cached sign-in asks for
+  expect(DEPLOY_SCOPES).not.toContain(BILLING_SCOPE);
+  expect(CARD_SCOPE).not.toBe(BILLING_SCOPE);
+
+  const calls: { path: string; form: Record<string, string> }[] = [];
+  const cloudflareSays = (granted: string) =>
+    vi.stubGlobal("fetch", async (url: string | URL, init?: RequestInit) => {
+      const path = new URL(String(url)).pathname;
+      const form = Object.fromEntries(new URLSearchParams(String(init?.body)));
+      calls.push({ path, form });
+      const answer = path.endsWith("/device/auth")
+        ? {
+            device_code: "device-1",
+            user_code: "ABCD-EFGH",
+            verification_uri: "https://dash.cloudflare.com/oauth2/device",
+            expires_in: 300,
+            interval: 1,
+          }
+        : path.endsWith("/token")
+          ? { access_token: "billing-token", expires_in: 3600, scope: granted }
+          : {};
+      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);
+  try {
+    cloudflareSays(BILLING_SCOPE);
+    let shown = "";
+    const made = await briefAccess(
+      [BILLING_SCOPE],
+      ({ code }) => {
+        shown = code;
+      },
+      async (token) => `acted with ${token}`,
+    );
+    expect(shown).toBe("ABCD-EFGH");
+    expect(made).toEqual({ lacks: [], done: "acted with billing-token" });
+    expect(calls[0]!.form.scope).toBe(BILLING_SCOPE);
+    expect(revoked()).toEqual(["billing-token"]);
+
+    // an act that throws: the access is ended all the same
+    calls.length = 0;
+    await expect(
+      briefAccess([BILLING_SCOPE], () => {}, async () => {
+        throw new Error("Cloudflare is down");
+      }),
+    ).rejects.toThrow("Cloudflare is down");
+    expect(revoked()).toEqual(["billing-token"]);
+
+    // an approval without the scope: no act, and the access is ended
+    calls.length = 0;
+    cloudflareSays("user-details.read");
+    let acted = false;
+    expect(
+      await briefAccess([BILLING_SCOPE], () => {}, async () => {
+        acted = true;
+      }),
+    ).toEqual({ lacks: [BILLING_SCOPE] });
+    expect(acted).toBe(false);
+    expect(revoked()).toEqual(["billing-token"]);
+  } finally {
+    vi.unstubAllGlobals();
+  }
 });
M core/lib/src/cli/cloudflare-access.ts
@@ -116,6 +116,13 @@
  *  (`keptSignInOf`) never does. */
 export const CARD_SCOPE = "aig.read";
 
+/** THE SCOPE THAT TURNS A PRODUCT OF THE ACCOUNT ON (Workers Paid, R2): Cloudflare's billing
+ *  write, which makes a subscription (`POST /accounts/<id>/subscriptions`). It can spend the
+ *  account's money, so NO SIGN-IN THAT IS KEPT EVER HOLDS IT: neither the one-hour sign-in in the
+ *  config folder nor a kept sign-in asks for it. Only `briefAccess` does, after the person said
+ *  yes to a product's price, and it ends that access when the act is done. */
+export const BILLING_SCOPE = "billing:write";
+
 /** WHAT `iterate recover` ASKS FOR: the reads that find the mind (its zone with the zone's
  *  account, the zone's routes, the boundary Worker's settings), and D1's write for the two
  *  statements. */
@@ -412,6 +419,25 @@
   );
   chmodSync(KEPT, 0o600);
   return { token: answer.access_token, from: "sign-in", lacks };
+}
+
+/** 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). */
+export async function briefAccess<T>(
+  scopes: readonly string[],
+  show: Parameters<typeof deviceSignIn>[1],
+  act: (token: string) => Promise<T>,
+): Promise<{ lacks: string[]; done?: T }> {
+  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 {
+    await revoke(answer.refresh_token);
+    await revoke(answer.access_token);
+  }
 }
 
 // ---------------------------------------------------------------------------------------------
M core/lib/src/cli/deploy.test.ts
@@ -6,6 +6,8 @@
 import { MindConfig as ScriptConfig } from "../../../alchemy/src/config.ts";
 import { DEPLOY_SCOPES, RECOVER_SCOPES, scopesLacking, STACK_SCOPES } from "./cloudflare-access.ts";
 import {
+  activationOffer,
+  activationOutcomeOf,
   alternativesOf,
   assertSupportedNodeVersion,
   boundaryCheck,
@@ -19,6 +21,9 @@
   deployStack,
   deployConfigOf,
   patternsRefusalOf,
+  planTermsOf,
+  PRODUCTS,
+  subscriptionBodyOf,
   deployedMind,
   domainPickerOptions,
   earlierDeployOf,
@@ -2189,3 +2194,187 @@
     },
   };
 }
+
+// What Cloudflare's public catalog answered on 27 Nov 2026 for the two rate plans
+// (GET /billing/rate_plans/<plan>, read with no credentials), cut to a few of their parts.
+const catalog = (result: unknown) => ({ status: 200, result, total: 0, error: "" });
+const workersPaidPlan = {
+  "id": "WORKERS_PAID",
+  "public_name": "Cloudflare Workers Paid",
+  "currency": "USD",
+  "components": [
+    {
+      "name": "account",
+      "publicName": "Base Monthly Fee",
+      "kind": "enum",
+      "type": "flatPricingComponent",
+      "aggregate": "",
+      "chargeType": "subscription",
+      "chargeModel": "flat",
+      "defaultQuantity": 1,
+      "tiers": [
+        {
+          "lowerThreshold": 1,
+          "upperThreshold": 1,
+          "pricingType": "fixed",
+          "price": 5,
+          "bucketSize": 0
+        }
+      ],
+      "discounts": {}
+    },
+    {
+      "name": "queues_enabled",
+      "publicName": "Queues",
+      "kind": "enum",
+      "type": "tieredPricingComponent",
+      "aggregate": "",
+      "features": [
+        "queues.enabled"
+      ],
+      "chargeType": "subscription",
+      "chargeModel": "tiered",
+      "defaultQuantity": 1,
+      "tiers": [
+        {
+          "lowerThreshold": 0,
+          "upperThreshold": 1,
+          "pricingType": "fixed",
+          "price": 0,
+          "bucketSize": 0
+        }
+      ],
+      "discounts": {}
+    }
+  ]
+};
+const r2Plan = {
+  "id": "R2_PAID",
+  "public_name": "R2 Storage",
+  "currency": "USD",
+  "components": [
+    {
+      "name": "base",
+      "publicName": "Base",
+      "kind": "enum",
+      "type": "flatPricingComponent",
+      "aggregate": "",
+      "chargeType": "subscription",
+      "chargeModel": "flat",
+      "defaultQuantity": 1,
+      "tiers": [
+        {
+          "lowerThreshold": 0,
+          "upperThreshold": 0,
+          "pricingType": "fixed",
+          "price": 0,
+          "bucketSize": 0
+        }
+      ],
+      "discounts": {}
+    },
+    {
+      "name": "r2_storage",
+      "publicName": "R2 Storage",
+      "kind": "usage",
+      "type": "tieredPricingComponent",
+      "metric": "r2_storage",
+      "aggregate": "sum",
+      "chargeType": "usage",
+      "chargeModel": "tiered",
+      "defaultQuantity": 0,
+      "tiers": [
+        {
+          "lowerThreshold": 0,
+          "upperThreshold": 0,
+          "pricingType": "unit",
+          "price": 0.015,
+          "bucketSize": 0
+        }
+      ],
+      "discounts": {},
+      "cfUOM": "GIGABYTE",
+      "cfQuantityLabel": "{{comma .}} GB-Month",
+      "cfStartOfFirstUnit": 300000000001,
+      "cfUsageDivisor": 30000000000,
+      "cfUsageID": "r2_storage"
+    }
+  ]
+};
+
+test("a product that is off is offered with its exact terms from Cloudflare's catalog, and only a yes makes the subscription", () => {
+  const terms = planTermsOf("workers_paid", catalog(workersPaidPlan));
+  expect(terms).toEqual({ plan: "workers_paid", name: "Cloudflare Workers Paid", monthly: 5 });
+  const offer = activationOffer({
+    product: "Workers Paid",
+    terms,
+    account: "Ada's Account",
+    card: "there",
+    person: true,
+  });
+  expect(offer!.question).toBe("Turn on Workers Paid now, for $5 a month?");
+  expect(offer!.words).toContain("Cloudflare Workers Paid, $5 a month");
+  expect(offer!.words).toContain("charges the payment card of the account Ada's Account");
+  expect(offer!.words).toContain("each month until you cancel it");
+  expect(offer!.words).toContain(PRODUCTS["Workers Paid"].pricing);
+  expect(offer!.words).toContain("After a no, you turn it on yourself");
+
+  // R2 has no monthly fee: the words promise no charge now, and still name the prices by use
+  const free = activationOffer({
+    product: "R2",
+    terms: planTermsOf("r2_paid", catalog(r2Plan)),
+    account: "Ada's Account",
+    card: "unknown",
+    person: true,
+  });
+  expect(free!.question).toBe("Turn on R2 now, for $0 a month?");
+  expect(free!.words).toContain("R2 Storage, $0 a month.");
+  expect(free!.words).not.toContain("charges the payment card");
+  expect(free!.words).toContain(PRODUCTS.R2.pricing);
+
+  // what the yes sends, and what Cloudflare's answer means
+  expect(subscriptionBodyOf(PRODUCTS.R2.plan)).toEqual({
+    rate_plan: { id: "r2_paid" },
+    frequency: "monthly",
+  });
+  expect(activationOutcomeOf({ status: 200, result: {}, total: 0, error: "" })).toEqual({ on: true });
+});
+
+test("no offer without certain terms, without a card, or with nobody at Cloudflare's page: the way by hand stays", () => {
+  const terms = planTermsOf("workers_paid", catalog(workersPaidPlan));
+  const base = { product: "Workers Paid" as const, terms, account: "A", card: "there" as const };
+  expect(activationOffer({ ...base, person: true })).toBeDefined();
+  // an API token, a kept sign-in, CI or a coding agent: nobody can approve the billing access
+  expect(activationOffer({ ...base, person: false })).toBeUndefined();
+  expect(activationOffer({ ...base, card: "none", person: true })).toBeUndefined();
+  expect(activationOffer({ ...base, terms: undefined, person: true })).toBeUndefined();
+
+  // terms that are not read for certain are no terms
+  expect(planTermsOf("workers_paid", undefined)).toBeUndefined();
+  expect(planTermsOf("workers_paid", { ...catalog(workersPaidPlan), status: 404 })).toBeUndefined();
+  expect(planTermsOf("r2_paid", catalog(workersPaidPlan))).toBeUndefined();
+  expect(
+    planTermsOf("workers_paid", catalog({ ...workersPaidPlan, currency: "EUR" })),
+  ).toBeUndefined();
+  expect(planTermsOf("workers_paid", catalog({ id: "WORKERS_PAID" }))).toBeUndefined();
+  const perUnit = structuredClone(workersPaidPlan);
+  perUnit.components[0]!.tiers[0]!.pricingType = "unit";
+  expect(planTermsOf("workers_paid", catalog(perUnit))).toBeUndefined();
+  const otherCharge = structuredClone(workersPaidPlan);
+  otherCharge.components[0]!.chargeType = "oneTime";
+  expect(planTermsOf("workers_paid", catalog(otherCharge))).toBeUndefined();
+});
+
+test("a subscription that Cloudflare refuses is not on, and its words are kept for the person", () => {
+  expect(
+    activationOutcomeOf({
+      status: 403,
+      result: undefined,
+      total: 0,
+      error: "Authentication error (code 10000)",
+    }),
+  ).toEqual({ on: false, why: "403: Authentication error (code 10000)" });
+  expect(
+    activationOutcomeOf({ status: 400, result: undefined, total: 0, error: "no payment method" }),
+  ).toEqual({ on: false, why: "400: no payment method" });
+});
M core/lib/src/cli/deploy.ts

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