diff --git a/packages/cli/src/auth/oauth.test.ts b/packages/cli/src/auth/oauth.test.ts index 8d4268af41..8c8bb6cdbb 100644 --- a/packages/cli/src/auth/oauth.test.ts +++ b/packages/cli/src/auth/oauth.test.ts @@ -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((r) => (called = r)); + const fetchImpl = ((_url: string, init?: RequestInit) => { + called(); + if (!init?.signal) return Promise.resolve(new Response("", { status: 500 })); + return new Promise((_, 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: { diff --git a/packages/cli/src/commands/billing.test.ts b/packages/cli/src/commands/billing.test.ts index 78e6dcf208..3b12eb16e7 100644 --- a/packages/cli/src/commands/billing.test.ts +++ b/packages/cli/src/commands/billing.test.ts @@ -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 | undefined, + checkout: undefined as Promise | 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(); 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() { + let resolve!: (value: T) => void; + const promise = new Promise((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(); + 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(); + 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(); + 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); + }); +}); diff --git a/packages/cli/src/commands/billing.ts b/packages/cli/src/commands/billing.ts index 7304c6d9c7..1187ccc6d1 100644 --- a/packages/cli/src/commands/billing.ts +++ b/packages/cli/src/commands/billing.ts @@ -51,7 +51,8 @@ async function openCheckout( source: CheckoutSource, ): Promise { 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 { - 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, diff --git a/packages/cli/src/heygen/plan.test.ts b/packages/cli/src/heygen/plan.test.ts index f585fea6e7..8ccf455030 100644 --- a/packages/cli/src/heygen/plan.test.ts +++ b/packages/cli/src/heygen/plan.test.ts @@ -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 }[] = []; vi.stubGlobal("fetch", async (url: string, init: { body: string }) => { diff --git a/packages/cli/src/heygen/plan.ts b/packages/cli/src/heygen/plan.ts index ef10eab8d1..9e06e55d52 100644 --- a/packages/cli/src/heygen/plan.ts +++ b/packages/cli/src/heygen/plan.ts @@ -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 { +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> { + if (!stop) return resolveCloudAuthHeaders(); + stop.throwIfAborted(); + const headers = await Promise.race([ + resolveCloudAuthHeaders(), + new Promise((_, 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 { 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 { +export async function readOffer(stop?: AbortSignal): Promise { 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 { 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): Promise { +async function postCheckout( + route: string, + body: Record, + stop?: AbortSignal, +): Promise { 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",