fix(cli): billing stops checkout work once the payment wait ends, even mid sign-in refresh (#7216)

* fix(cli): billing stops checkout work once the payment wait ends, and a token refresh can't hang it

The wait for a purchase ends when the account shows it or at --timeout.
Checkout work still in flight then kept going: a price read that answered
late still created and printed a checkout, an Enter-time checkout that
answered late still opened Stripe, and the command waited on that work
past the purchase or the deadline. A token refresh with no deadline could
hold any of these reads forever.

readPlan, readOffer and createCheckout take the wait's stop signal, joined
with their own deadline, and stop waiting on a sign-in refresh once it
fires. Billing checks it after the price read and after each checkout
before printing or opening anything. The token refresh POST gives up
after 20 s.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01HebQXN7wsMK6GqT3MNtqXw

* refactor(cli): billing's checkout failure and its two billing reads each live in one place

The comment-share ratchet and the fallow audit failed on #7216: a new comment
in billing.ts, readPlan and readOffer repeating the same eight-line request,
and offerCheckout over the complexity threshold. The reads share getBilling,
the failure report moves to reportCheckoutFailure, and the comment goes.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01HebQXN7wsMK6GqT3MNtqXw

* fix(cli): billing's stop signal fires at --timeout, not only when the poll returns

The checkout path stopped once the polling task ended, but the poll's
readPlan carried no signal. A poll read stalled across the deadline kept the
signal live, so a held offer could still create and print a checkout after
--timeout. A timer now aborts the controller at the deadline on its own, the
initial and polling plan reads take the same signal, and the deadline counts
from the start of the command.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01HebQXN7wsMK6GqT3MNtqXw

---------

Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
WaterrrForever
2026-11-05 06:14:27 +00:00
committed by GitHub
co-authored by Claude Opus 5.5
parent 1fecf5b82a
commit 060e6e4a12
5 changed files with 255 additions and 51 deletions
+23
View File
@@ -3,6 +3,7 @@ import { promises as fs } from "node:fs";
import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";
import { setupTempAuthEnv } from "./_test-utils.js";
import { openBrowser } from "./browser.js";
import { ACCOUNT_REQUEST_TIMEOUT_MS } from "./client.js";
import { isAuthError } from "./errors.js";
import { startLoopback } from "./loopback.js";
import {
@@ -230,6 +231,28 @@ describe("auth/oauth", () => {
expect(credentials.oauth).toMatchObject({ ...oauthIdentity(), access_token: "new_at" });
});
it("gives up on a refresh the token endpoint never answers, so a caller is not held forever", async () => {
process.env["HEYGEN_API_URL"] = "https://api.test.example";
await writeStore({ oauth: { access_token: "old_at", refresh_token: "stall_rt" } });
const deadline = new AbortController();
const timeout = vi.spyOn(AbortSignal, "timeout").mockReturnValue(deadline.signal);
let called!: () => void;
const fetched = new Promise<void>((r) => (called = r));
const fetchImpl = ((_url: string, init?: RequestInit) => {
called();
if (!init?.signal) return Promise.resolve(new Response("", { status: 500 }));
return new Promise<Response>((_, reject) =>
init.signal?.addEventListener("abort", () => reject(new Error("refresh timed out"))),
);
}) as unknown as typeof fetch;
const refresh = refreshTokens("stall_rt", { fetchImpl });
await fetched;
deadline.abort();
await expect(refresh).rejects.toThrow();
expect(timeout).toHaveBeenCalledWith(ACCOUNT_REQUEST_TIMEOUT_MS);
timeout.mockRestore();
});
it("preserves the prior refresh_token when the server omits it (no rotation)", async () => {
await writeStore({
oauth: {
+144 -12
View File
@@ -9,9 +9,18 @@ const terminal = vi.hoisted(() => ({
checkouts: 0,
checkoutError: null as unknown,
args: [] as unknown[][],
enter: false,
}));
const events = vi.hoisted(() => ({ failed: [] as unknown[], timeout: [] as unknown[] }));
const never = vi.hoisted(() => ({ paid: true }));
const held = vi.hoisted(() => ({
offer: undefined as Promise<object> | undefined,
checkout: undefined as Promise<string> | undefined,
realOffer: false,
headerCalls: 0,
holdHeadersAfter: undefined as number | undefined,
stallPoll: false,
}));
vi.mock("../telemetry/events.js", () => ({
trackBillingCheckoutFailed: (p: unknown) => void events.failed.push(p),
@@ -22,10 +31,12 @@ vi.mock("../utils/attendedTerminal.js", () => ({ isUnattended: () => !terminal.a
vi.mock("node:readline/promises", () => ({
createInterface: () => ({
question: (_q: string, opts: { signal: AbortSignal }) =>
new Promise((_resolve, reject) =>
opts.signal.addEventListener("abort", () =>
reject(Object.assign(new Error("aborted"), { name: "AbortError" })),
),
new Promise((resolve, reject) =>
terminal.enter
? resolve("")
: opts.signal.addEventListener("abort", () =>
reject(Object.assign(new Error("aborted"), { name: "AbortError" })),
),
),
close: () => undefined,
}),
@@ -35,24 +46,32 @@ vi.mock("../auth/browser.js", () => ({
openBrowser: async (url: string) => void opened.push(url),
}));
vi.mock("../cloud/auth.js", () => ({
resolveCloudAuthHeaders: async () => ({ "x-api-key": "k" }),
resolveCloudAuthHeaders: () =>
held.holdHeadersAfter !== undefined && ++held.headerCalls > held.holdHeadersAfter
? new Promise(() => undefined)
: Promise.resolve({ "x-api-key": "k" }),
resolveCloudBaseUrl: () => "https://api.example.test",
}));
vi.mock("../heygen/plan.js", async (importOriginal) => {
const real = await importOriginal<typeof import("../heygen/plan.js")>();
return {
...real,
readOffer: async () => ({}),
readOffer: async (stop?: AbortSignal) =>
held.realOffer ? real.readOffer(stop) : (held.offer ?? {}),
createCheckout: async (...args: unknown[]) => {
if (terminal.checkoutError) throw terminal.checkoutError;
terminal.checkouts++;
terminal.args.push(args);
return "https://checkout.stripe.com/c/pay/cs_test_1";
return held.checkout ?? "https://checkout.stripe.com/c/pay/cs_test_1";
},
readPlan: async (stop?: AbortSignal) => {
if (++plan.calls > 1 && held.stallPoll)
return new Promise((resolve) => stop?.addEventListener("abort", () => resolve(null)));
return {
plan: plan.calls === 1 || !never.paid ? "none" : "pro",
credits: plan.calls === 1 || !never.paid ? 0 : 500,
};
},
readPlan: async () => ({
plan: ++plan.calls === 1 || !never.paid ? "none" : "pro",
credits: plan.calls === 1 || !never.paid ? 0 : 500,
}),
};
});
@@ -73,9 +92,18 @@ afterEach(() => {
terminal.checkouts = 0;
terminal.args.length = 0;
terminal.checkoutError = null;
terminal.enter = false;
events.failed.length = 0;
events.timeout.length = 0;
never.paid = true;
Object.assign(held, {
offer: undefined,
checkout: undefined,
realOffer: false,
headerCalls: 0,
holdHeadersAfter: undefined,
stallPoll: false,
});
vi.restoreAllMocks();
consumeCommandResult();
});
@@ -109,7 +137,12 @@ describe("billing subscribe", () => {
expect(url.searchParams.get("from")).toBe("cli");
expect(url.searchParams.get("skill")).toBe("style-sampling");
expect(terminal.args).toEqual([
["plans", {}, undefined, { skill: "style-sampling", baseline: 0 }],
[
"plans",
{},
undefined,
{ skill: "style-sampling", baseline: 0, stop: expect.any(AbortSignal) },
],
]);
});
});
@@ -237,3 +270,102 @@ describe("billing outcomes", () => {
expect(events.timeout).toEqual([]);
});
});
function release<T>() {
let resolve!: (value: T) => void;
const promise = new Promise<T>((r) => (resolve = r));
return { promise, resolve };
}
describe("billing once the wait has ended", () => {
it("creates no checkout when the purchase lands while the price is still being read", async () => {
const log = vi.spyOn(console, "log").mockImplementation(() => undefined);
const offer = release<object>();
held.offer = offer.promise;
vi.useFakeTimers();
const done = runCommand(billing, { rawArgs: ["subscribe"] });
await vi.advanceTimersByTimeAsync(2000);
offer.resolve({ pro: { amount: 2900, currency: "usd" } });
await done;
vi.useRealTimers();
expect(terminal.checkouts).toBe(0);
expect(log.mock.calls.flat().join("\n")).not.toContain("Checkout link");
});
it("opens no checkout page when the purchase lands while Enter's checkout is being created", async () => {
terminal.attended = true;
terminal.enter = true;
vi.spyOn(console, "log").mockImplementation(() => undefined);
const checkout = release<string>();
held.checkout = checkout.promise;
vi.useFakeTimers();
const done = runCommand(billing, { rawArgs: ["subscribe"] });
await vi.advanceTimersByTimeAsync(2000);
checkout.resolve("https://checkout.stripe.com/c/pay/cs_late");
await done;
vi.useRealTimers();
expect(opened.map((u) => new URL(u).hostname)).toEqual(["hyperframes.studio"]);
});
it("ends at --timeout while the price read is still unanswered", async () => {
vi.spyOn(console, "log").mockImplementation(() => undefined);
vi.spyOn(console, "error").mockImplementation(() => undefined);
held.realOffer = true;
never.paid = false;
vi.stubGlobal("fetch", async (url: string, init?: RequestInit) =>
String(url).includes("/hyperframes/plans")
? new Promise((_, reject) =>
init?.signal?.addEventListener("abort", () => reject(init.signal?.reason)),
)
: new Response(JSON.stringify({ data: { space_info: { space_id: "sp-1" } } })),
);
vi.useFakeTimers();
let settled = false;
const done = runCommand(billing, { rawArgs: ["subscribe", "--timeout", "4"] }).then(
() => (settled = true),
() => (settled = true),
);
await vi.advanceTimersByTimeAsync(6000);
vi.useRealTimers();
expect(settled).toBe(true);
await done;
expect(terminal.checkouts).toBe(0);
});
it("creates no checkout after --timeout while a plan poll is still unanswered", async () => {
const log = vi.spyOn(console, "log").mockImplementation(() => undefined);
vi.spyOn(console, "error").mockImplementation(() => undefined);
never.paid = false;
held.stallPoll = true;
const offer = release<object>();
held.offer = offer.promise;
vi.useFakeTimers();
let settled = false;
const done = runCommand(billing, { rawArgs: ["subscribe", "--timeout", "4"] }).then(
() => (settled = true),
() => (settled = true),
);
await vi.advanceTimersByTimeAsync(6000);
offer.resolve({ pro: { amount: 2900, currency: "usd" } });
await vi.advanceTimersByTimeAsync(0);
vi.useRealTimers();
expect(terminal.checkouts).toBe(0);
expect(log.mock.calls.flat().join("\n")).not.toContain("Checkout link");
expect(settled).toBe(true);
await done;
});
it("ends when the purchase lands while a sign-in refresh is still unanswered", async () => {
vi.spyOn(console, "log").mockImplementation(() => undefined);
held.realOffer = true;
held.holdHeadersAfter = 1; // the plans page's workspace read answers; the price read's does not
let settled = false;
vi.useFakeTimers();
const done = runCommand(billing, { rawArgs: ["subscribe"] }).then(() => (settled = true));
await vi.advanceTimersByTimeAsync(2000);
vi.useRealTimers();
expect(settled).toBe(true);
await done;
expect(terminal.checkouts).toBe(0);
});
});
+26 -14
View File
@@ -51,7 +51,8 @@ async function openCheckout(
source: CheckoutSource,
): Promise<void> {
if (isUnattended()) {
console.log(`Checkout link: ${c.accent(await createCheckout(kind, offer, missing, source))}`);
const link = await createCheckout(kind, offer, missing, { ...source, stop: signal });
if (!signal.aborted) console.log(`Checkout link: ${c.accent(link)}`);
return;
}
const rl = createInterface({ input: process.stdin, output: process.stdout });
@@ -60,7 +61,9 @@ async function openCheckout(
} finally {
rl.close();
}
await openBrowser(await createCheckout(kind, offer, missing, source));
if (signal.aborted) return;
const link = await createCheckout(kind, offer, missing, { ...source, stop: signal });
if (!signal.aborted) await openBrowser(link);
}
async function offerCheckout(
@@ -70,7 +73,8 @@ async function offerCheckout(
needed: number | undefined,
source: CheckoutSource,
): Promise<CheckoutError | null> {
const offer = await readOffer();
const offer = await readOffer(signal);
if (signal.aborted) return null;
const missing = needed ? needed - (before?.credits ?? 0) : undefined;
const line = priceLine(kind, offer, missing, needed);
if (line) console.log(line);
@@ -78,14 +82,17 @@ async function offerCheckout(
await openCheckout(kind, offer, missing, signal, source);
return null;
} catch (error) {
if (signal.aborted) return null;
console.error(c.error(error instanceof Error ? error.message : String(error)));
if (!(error instanceof CheckoutError)) return null;
trackBillingCheckoutFailed({ reason: error.reason });
return error;
return signal.aborted ? null : reportCheckoutFailure(error);
}
}
function reportCheckoutFailure(error: unknown): CheckoutError | null {
console.error(c.error(error instanceof Error ? error.message : String(error)));
if (!(error instanceof CheckoutError)) return null;
trackBillingCheckoutFailed({ reason: error.reason });
return error;
}
/** Opens the plans or credits page, then waits until the account shows the change, so the run continues on its own. */
export default defineCommand({
meta: {
@@ -121,7 +128,11 @@ export default defineCommand({
}
const needed = Number(args.needed) || undefined;
const skill = checkoutSkill(args.skill);
const before = await readPlan();
const deadline = Date.now() + (Number(args.timeout) || 600) * 1000;
const stop = new AbortController();
const atDeadline = setTimeout(() => stop.abort(), deadline - Date.now());
atDeadline.unref?.();
const before = await readPlan(stop.signal);
const done = (p: Plan | null) =>
action === "subscribe"
? !!p && p.plan !== "none"
@@ -139,17 +150,18 @@ export default defineCommand({
});
console.log(`${action === "subscribe" ? "Plans" : "Credits"} page: ${c.accent(url)}`);
await openBrowser(url);
const deadline = Date.now() + (Number(args.timeout) || 600) * 1000;
const stop = new AbortController();
const giveUp = new AbortController();
const waiting = (async () => {
while (Date.now() < deadline && !giveUp.signal.aborted) {
while (!stop.signal.aborted && !giveUp.signal.aborted) {
await new Promise((r) => setTimeout(r, 2000));
const now = await readPlan();
const now = await readPlan(stop.signal);
if (done(now)) return now;
}
return null;
})().finally(() => stop.abort());
})().finally(() => {
clearTimeout(atDeadline);
stop.abort();
});
const checkoutFailure = await offerCheckout(
action === "subscribe" ? "plans" : "credits",
before,
+13
View File
@@ -160,6 +160,19 @@ describe("stripeCheckoutUrl", () => {
});
describe("createCheckout", () => {
it("sends no checkout once the wait it belongs to has ended", async () => {
const fetchImpl = vi.fn(async () => new Response("{}"));
vi.stubGlobal("fetch", fetchImpl);
const stop = new AbortController();
stop.abort();
await expect(
createCheckout("plans", { pro: { amount: 2900, currency: "usd" } }, undefined, {
stop: stop.signal,
}),
).rejects.toBeDefined();
expect(fetchImpl).not.toHaveBeenCalled();
});
it("asks for Pro with the CLI's own token and returns Stripe's page", async () => {
const sent: { url: string; body: Record<string, unknown> }[] = [];
vi.stubGlobal("fetch", async (url: string, init: { body: string }) => {
+49 -25
View File
@@ -28,14 +28,35 @@ function mockPlan(): Plan | null {
// Payment routes live on api2, beside the OAuth ones; the v3 generation routes stay on api.
export const billingBaseUrl = () => resolveCloudBaseUrl().replace("://api.", "://api2.");
export async function readPlan(): Promise<Plan | null> {
const timeoutOrStop = (ms: number, stop?: AbortSignal) =>
stop ? AbortSignal.any([stop, AbortSignal.timeout(ms)]) : AbortSignal.timeout(ms);
// A token refresh can't take the stop signal: overlapping callers share the one in-flight refresh.
async function authHeadersUnlessStopped(stop?: AbortSignal): Promise<Record<string, string>> {
if (!stop) return resolveCloudAuthHeaders();
stop.throwIfAborted();
const headers = await Promise.race([
resolveCloudAuthHeaders(),
new Promise<never>((_, reject) =>
stop.addEventListener("abort", () => reject(stop.reason), { once: true }),
),
]);
stop.throwIfAborted();
return headers;
}
async function getBilling(route: string, stop?: AbortSignal) {
const res = await fetch(`${billingBaseUrl()}/v1/payment/hyperframes/${route}`, {
headers: { ...(await authHeadersUnlessStopped(stop)), accept: "application/json" },
signal: timeoutOrStop(15_000, stop),
});
const body: unknown = await res.json().catch(() => null);
return { res, data: isRecord(body) && isRecord(body.data) ? body.data : body };
}
export async function readPlan(stop?: AbortSignal): Promise<Plan | null> {
try {
const res = await fetch(`${billingBaseUrl()}/v1/payment/hyperframes/subscription`, {
headers: { ...(await resolveCloudAuthHeaders()), accept: "application/json" },
signal: AbortSignal.timeout(15_000),
});
const body: unknown = await res.json().catch(() => null);
const data = isRecord(body) && isRecord(body.data) ? body.data : body;
const { res, data } = await getBilling("subscription", stop);
if (!res.ok || !isRecord(data)) return mockPlan();
const usage = isRecord(data.usage) ? data.usage : {};
// studio-contracts' BillingSubscription: `subscription` is null on Free; an unpaid placeholder still names a plan.
@@ -126,14 +147,9 @@ export interface Offer {
const int = (v: unknown) =>
Number.isSafeInteger(v) && (v as number) > 0 ? (v as number) : undefined;
export async function readOffer(): Promise<Offer> {
export async function readOffer(stop?: AbortSignal): Promise<Offer> {
try {
const res = await fetch(`${billingBaseUrl()}/v1/payment/hyperframes/plans`, {
headers: { ...(await resolveCloudAuthHeaders()), accept: "application/json" },
signal: AbortSignal.timeout(15_000),
});
const body: unknown = await res.json().catch(() => null);
const data = isRecord(body) && isRecord(body.data) ? body.data : body;
const { res, data } = await getBilling("plans", stop);
if (!res.ok || !isRecord(data)) return {};
const plans = Array.isArray(data.plans) ? data.plans.filter(isRecord) : [];
const pro = plans.find((p) => p.plan_name === "pro" && p.period === "month");
@@ -213,7 +229,7 @@ export async function createCheckout(
kind: "plans" | "credits",
offer: Offer,
missing?: number,
source: { skill?: string; baseline?: number } = {},
source: { skill?: string; baseline?: number; stop?: AbortSignal } = {},
): Promise<string> {
const addon = kind === "credits" ? offer.addon : undefined;
if (kind === "credits" && !addon)
@@ -222,34 +238,42 @@ export async function createCheckout(
"Credits are not on sale for this account right now.",
);
if (addon)
return postCheckout("addon.checkout", {
quantity: addonBlocks(addon, missing),
currency: addon.currency,
unit_amount: addon.unitAmount,
});
return postCheckout(
"addon.checkout",
{
quantity: addonBlocks(addon, missing),
currency: addon.currency,
unit_amount: addon.unitAmount,
},
source.stop,
);
const pro = () => ({ plan_name: "pro", period: "month", request_id: randomUUID() });
const returnUrl = cliCheckoutReturn(checkoutSkill(source.skill), source.baseline);
try {
return await postCheckout("checkout", { ...pro(), return_url: returnUrl });
return await postCheckout("checkout", { ...pro(), return_url: returnUrl }, source.stop);
} catch (error) {
// A server whose allow-list lacks the plans page still sells Pro, only without the CLI's origin.
const refused = error instanceof CheckoutError && error.reason === "checkout_rejected";
if (!refused || !RETURN_REFUSED.test(error.message)) throw error;
trackBillingCheckoutReturnRefused();
return postCheckout("checkout", pro());
return postCheckout("checkout", pro(), source.stop);
}
}
async function postCheckout(route: string, body: Record<string, unknown>): Promise<string> {
async function postCheckout(
route: string,
body: Record<string, unknown>,
stop?: AbortSignal,
): Promise<string> {
const res = await fetch(`${billingBaseUrl()}/v1/payment/hyperframes/${route}`, {
method: "POST",
headers: {
...(await resolveCloudAuthHeaders()),
...(await authHeadersUnlessStopped(stop)),
accept: "application/json",
"content-type": "application/json",
},
body: JSON.stringify(body),
signal: AbortSignal.timeout(20_000),
signal: timeoutOrStop(20_000, stop),
}).catch((error: unknown) => {
throw new CheckoutError(
"checkout_network",