Skip to content

Commit 728bccb

Browse files
fix(cli): a stalled sign-in refresh no longer holds billing past its stop
The token refresh request gets a 20 s deadline, for every caller, and the billing reads race the sign-in against the stop signal, so payment or the timeout ends the command even while the token is still refreshing.
1 parent f243f86 commit 728bccb

4 files changed

Lines changed: 35 additions & 4 deletions

File tree

‎packages/cli/src/auth/oauth.test.ts‎

Lines changed: 3 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -205,8 +205,10 @@ describe("auth/oauth", () => {
205205
process.env["HEYGEN_API_URL"] = "https://api.test.example";
206206
await writeStore({ oauth: { access_token: "old_at", refresh_token: "old_rt" } });
207207
let capturedBody: string | undefined;
208+
let capturedSignal: AbortSignal | null | undefined;
208209
const fetchImpl = (async (_url: string, init?: RequestInit) => {
209210
capturedBody = init?.body as string;
211+
capturedSignal = init?.signal;
210212
return new Response(
211213
JSON.stringify({
212214
access_token: "new_at",
@@ -224,6 +226,7 @@ describe("auth/oauth", () => {
224226
expect(tokens.refresh_token).toBe("new_rt");
225227
expect(capturedBody).toContain("grant_type=refresh_token");
226228
expect(capturedBody).toContain("refresh_token=old_rt");
229+
expect(capturedSignal).toBeInstanceOf(AbortSignal);
227230

228231
// Should have persisted.
229232
const { credentials } = await readStore();

‎packages/cli/src/auth/oauth.ts‎

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -356,6 +356,7 @@ function retryAfterSeconds(response: Response, nowMs: number): number | undefine
356356
}
357357

358358
const refreshing = new Map<string, Promise<OAuthTokens>>();
359+
const REFRESH_TIMEOUT_MS = 20_000;
359360

360361
/** Refresh the stored login. Calls that overlap in this process share one request, since the server rotates the token. */
361362
export function refreshTokens(
@@ -388,6 +389,7 @@ async function refreshOnce(refresh_token: string, opts: RefreshOptions): Promise
388389
accept: "application/json",
389390
},
390391
body: body.toString(),
392+
signal: AbortSignal.timeout(REFRESH_TIMEOUT_MS),
391393
});
392394

393395
if (res.status === 400 || res.status === 401) {

‎packages/cli/src/heygen/plan.test.ts‎

Lines changed: 16 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1,7 +1,9 @@
11
import { afterEach, describe, expect, it, vi } from "vitest";
22

3+
const auth = vi.hoisted(() => ({ parked: false }));
34
vi.mock("../cloud/auth.js", () => ({
4-
resolveCloudAuthHeaders: async () => ({ "x-api-key": "k" }),
5+
resolveCloudAuthHeaders: () =>
6+
auth.parked ? new Promise(() => undefined) : Promise.resolve({ "x-api-key": "k" }),
57
resolveCloudBaseUrl: () => "https://api.example.test",
68
}));
79

@@ -16,6 +18,7 @@ const answer = (data: unknown) =>
1618
});
1719

1820
afterEach(() => {
21+
auth.parked = false;
1922
vi.unstubAllGlobals();
2023
vi.unstubAllEnvs();
2124
});
@@ -138,3 +141,15 @@ describe("createCheckout", () => {
138141
expect(sent[0]).toEqual({ quantity: 3, currency: "usd", unit_amount: 100 });
139142
});
140143
});
144+
145+
describe("a stop while signing in", () => {
146+
it("returns at once from every billing read when the sign-in is still refreshing", async () => {
147+
auth.parked = true;
148+
const stop = new AbortController();
149+
const reads = [readPlan(stop.signal), readOffer(stop.signal)];
150+
const checkout = createCheckout("plans", {}, undefined, stop.signal).catch((e: unknown) => e);
151+
stop.abort();
152+
expect(await Promise.all(reads)).toEqual([null, {}]);
153+
expect(await checkout).toBeInstanceOf(Error);
154+
});
155+
});

‎packages/cli/src/heygen/plan.ts‎

Lines changed: 14 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -28,10 +28,21 @@ const billingBaseUrl = () => resolveCloudBaseUrl().replace("://api.", "://api2."
2828
const timeoutOrStop = (ms: number, stop?: AbortSignal) =>
2929
stop ? AbortSignal.any([stop, AbortSignal.timeout(ms)]) : AbortSignal.timeout(ms);
3030

31+
const authHeadersUnlessStopped = (stop?: AbortSignal): Promise<Record<string, string>> =>
32+
stop
33+
? Promise.race([
34+
resolveCloudAuthHeaders(),
35+
new Promise<never>((_, reject) => {
36+
if (stop.aborted) reject(stop.reason);
37+
stop.addEventListener("abort", () => reject(stop.reason), { once: true });
38+
}),
39+
])
40+
: resolveCloudAuthHeaders();
41+
3142
export async function readPlan(stop?: AbortSignal): Promise<Plan | null> {
3243
try {
3344
const res = await fetch(`${billingBaseUrl()}/v1/payment/hyperframes/subscription`, {
34-
headers: { ...(await resolveCloudAuthHeaders()), accept: "application/json" },
45+
headers: { ...(await authHeadersUnlessStopped(stop)), accept: "application/json" },
3546
signal: timeoutOrStop(15_000, stop),
3647
});
3748
const body: unknown = await res.json().catch(() => null);
@@ -88,7 +99,7 @@ const int = (v: unknown) =>
8899
export async function readOffer(stop?: AbortSignal): Promise<Offer> {
89100
try {
90101
const res = await fetch(`${billingBaseUrl()}/v1/payment/hyperframes/plans`, {
91-
headers: { ...(await resolveCloudAuthHeaders()), accept: "application/json" },
102+
headers: { ...(await authHeadersUnlessStopped(stop)), accept: "application/json" },
92103
signal: timeoutOrStop(15_000, stop),
93104
});
94105
const body: unknown = await res.json().catch(() => null);
@@ -164,7 +175,7 @@ export async function createCheckout(
164175
{
165176
method: "POST",
166177
headers: {
167-
...(await resolveCloudAuthHeaders()),
178+
...(await authHeadersUnlessStopped(stop)),
168179
accept: "application/json",
169180
"content-type": "application/json",
170181
},

0 commit comments

Comments
 (0)