Skip to content

Commit 34ddced

Browse files
vanceingallsclaude
andauthored
fix(cli): keep browser sign-in open through checkout (#6879)
* fix(cli): keep browser sign-in open through checkout The loopback listener timed out after 5 minutes, but plan checkout runs inside the OAuth flow. A slower purchase ended on ERR_CONNECTION_REFUSED. Raise the default to 60 minutes, matching pacific's plan-checkout handoff. Co-Authored-By: Claude Sonnet 5.5 <[email protected]> * fix(cli): show the sign-in limit and how to recover The waiting line now states the 60-minute limit and Ctrl+C. After a timed-out browser login the CLI says to run auth login again. Co-Authored-By: Claude Sonnet 5.5 <[email protected]> * fix(cli): drop unverified purchase claim, harden timer test, document limit Review fixes: the timeout hint no longer says purchases stay on the account (the CLI cannot observe billing); the no-timer-left test now asserts before any explicit close() and uses node:http so undici timers cannot pollute the count; docs mention the 60-minute window and Ctrl+C. Co-Authored-By: Claude Sonnet 5.5 <[email protected]> * fix(cli): close the sign-in listener on every path and record Ctrl+C Ctrl+C is now the advertised exit, but events only flush on exit, which a default SIGINT skips, so an abandoned login vanished from telemetry. Record it as aborted and exit 130 through requestCliExit. Close the listener on any throw, so a failure before the wait can't hold the process for the full window. Derive the waiting line and timeout message from the listener's own limit, and name the constant for why it is long, which clears the comment ratchet. Co-Authored-By: Claude Opus 5.5 <[email protected]> --------- Co-authored-by: Claude Sonnet 5.5 <[email protected]>
1 parent 0ab4931 commit 34ddced

8 files changed

Lines changed: 157 additions & 33 deletions

File tree

‎docs/packages/cli.mdx‎

Lines changed: 5 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -2282,6 +2282,11 @@ Opens a browser for OAuth:
22822282
hyperframes auth login
22832283
```
22842284

2285+
The command waits up to 60 minutes for you to finish in the browser, including
2286+
choosing a plan and checking out. Press Ctrl+C to cancel. If it times out, run
2287+
it again. On SSH or headless machines, where the browser can't reach this
2288+
machine, use `hyperframes auth login --device`.
2289+
22852290
Pass `--api-key` when you want a long-lived HeyGen API key instead. The key is
22862291
verified against `GET /v3/users/me` before the command reports success, so a
22872292
rejected key is never left on disk.

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

Lines changed: 34 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1,10 +1,12 @@
1-
import { afterEach, describe, expect, it } from "vitest";
1+
import { get } from "node:http";
2+
import { afterEach, describe, expect, it, vi } from "vitest";
23
import { startLoopback, type LoopbackHandle } from "./loopback.js";
34

45
describe("auth/loopback", () => {
56
let active: LoopbackHandle | null = null;
67

78
afterEach(async () => {
9+
vi.useRealTimers();
810
if (active) {
911
await active.close().catch(() => {});
1012
active = null;
@@ -73,4 +75,35 @@ describe("auth/loopback", () => {
7375
// Flow is still waiting — kill it via timeout.
7476
await expect(handle.result).rejects.toThrow(/timed out/i);
7577
});
78+
79+
// Literal on purpose: pins the default. Sign-in can include Stripe checkout.
80+
const CHECKOUT_WINDOW_MS = 60 * 60 * 1000;
81+
82+
it("accepts a callback after a slow checkout and leaves no timer behind", async () => {
83+
vi.useFakeTimers({ toFake: ["setTimeout", "clearTimeout"] });
84+
const handle = await startLoopback({ state: "s" });
85+
active = handle;
86+
await vi.advanceTimersByTimeAsync(CHECKOUT_WINDOW_MS - 1_000);
87+
// node:http, not fetch: undici registers its own timers, which would pollute the count.
88+
get(`${handle.redirectUri}?code=the_code&state=s`).on("error", () => {});
89+
await expect(handle.result).resolves.toMatchObject({ code: "the_code" });
90+
// Checked before any explicit close(): the flow must clean up after itself on success,
91+
// or the CLI stays alive for the whole window after "Signed in".
92+
expect(vi.getTimerCount()).toBe(0);
93+
await handle.close();
94+
});
95+
96+
it("gives up at the checkout window, not before", async () => {
97+
vi.useFakeTimers({ toFake: ["setTimeout", "clearTimeout"] });
98+
const handle = await startLoopback({ state: "s" });
99+
active = handle;
100+
const settled = vi.fn();
101+
handle.result.catch(settled);
102+
await vi.advanceTimersByTimeAsync(CHECKOUT_WINDOW_MS - 1);
103+
expect(settled).not.toHaveBeenCalled();
104+
expect(handle.timeoutLabel).toBe("60 minutes");
105+
const rejected = expect(handle.result).rejects.toThrow(/timed out after 60 minutes/i);
106+
await vi.advanceTimersByTimeAsync(1);
107+
await rejected;
108+
});
76109
});

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

Lines changed: 8 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -10,7 +10,7 @@
1010
* redirect URI's port is just a placeholder — the actual port the
1111
* server lands on is what matters at runtime.
1212
*
13-
* Times out after 120s. Validates `state` matches the value we
13+
* Times out after 60 minutes. Validates `state` matches the value we
1414
* generated. Renders a small "you can close this window" page back
1515
* to the browser before shutting down.
1616
*/
@@ -22,7 +22,7 @@ import { AddressInfo } from "node:net";
2222
export interface LoopbackOptions {
2323
/** Expected `state` value — flow fails if it doesn't match. */
2424
state: string;
25-
/** Timeout in ms (default 120s). */
25+
/** Timeout in ms (default 60 minutes). */
2626
timeoutMs?: number;
2727
/** Override port for tests (default 0 = ephemeral). */
2828
port?: number;
@@ -40,15 +40,17 @@ export interface LoopbackHandle {
4040
result: Promise<LoopbackResult>;
4141
/** Redirect URI to pass to /v1/oauth/authorize. */
4242
redirectUri: string;
43+
timeoutLabel: string;
4344
/** Stop the server early (e.g. user cancels). */
4445
close: () => Promise<void>;
4546
}
4647

4748
const CALLBACK_PATH = "/oauth/callback";
48-
const DEFAULT_TIMEOUT_MS = 300_000;
49+
const SIGN_IN_WITH_CHECKOUT_TIMEOUT_MS = 60 * 60 * 1000;
4950

5051
export async function startLoopback(opts: LoopbackOptions): Promise<LoopbackHandle> {
51-
const timeoutMs = opts.timeoutMs ?? DEFAULT_TIMEOUT_MS;
52+
const timeoutMs = opts.timeoutMs ?? SIGN_IN_WITH_CHECKOUT_TIMEOUT_MS;
53+
const timeoutLabel = `${timeoutMs / 60_000} minutes`;
5254

5355
let resolveResult!: (value: LoopbackResult) => void;
5456
let rejectResult!: (err: Error) => void;
@@ -88,14 +90,14 @@ export async function startLoopback(opts: LoopbackOptions): Promise<LoopbackHand
8890
};
8991

9092
const timer = setTimeout(() => {
91-
rejectResult(new Error(`OAuth callback timed out after ${timeoutMs}ms`));
93+
rejectResult(new Error(`OAuth callback timed out after ${timeoutLabel}`));
9294
void close();
9395
}, timeoutMs);
9496

9597
// When result settles, drain the timer + shutdown.
9698
result.finally(close).catch(() => {});
9799

98-
return { result, redirectUri, close };
100+
return { result, redirectUri, timeoutLabel, close };
99101
}
100102

101103
async function listen(server: Server, port: number): Promise<void> {

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

Lines changed: 34 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -2,7 +2,9 @@ import { oauthIdentity } from "./config.js";
22
import { promises as fs } from "node:fs";
33
import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";
44
import { setupTempAuthEnv } from "./_test-utils.js";
5+
import { openBrowser } from "./browser.js";
56
import { isAuthError } from "./errors.js";
7+
import { startLoopback } from "./loopback.js";
68
import {
79
parseTokenResponse,
810
persistFreshOAuth,
@@ -23,6 +25,7 @@ vi.mock("./loopback.js", () => ({
2325
redirectUri: "http://127.0.0.1:12345/oauth/callback",
2426
}),
2527
redirectUri: "http://127.0.0.1:12345/oauth/callback",
28+
timeoutLabel: "60 minutes",
2629
close: vi.fn(async () => {}),
2730
})),
2831
}));
@@ -411,6 +414,37 @@ describe("auth/oauth", () => {
411414
});
412415
});
413416

417+
describe("startAuthorizationCodeFlow listener", () => {
418+
const loopbackStub = (timeoutLabel: string) => ({
419+
result: new Promise<never>(() => {}),
420+
redirectUri: "http://127.0.0.1:12345/oauth/callback",
421+
timeoutLabel,
422+
close: vi.fn(async () => {}),
423+
});
424+
425+
it("closes the listener when the browser step throws", async () => {
426+
const loopback = loopbackStub("60 minutes");
427+
vi.mocked(startLoopback).mockResolvedValueOnce(loopback);
428+
vi.mocked(openBrowser).mockRejectedValueOnce(new Error("no browser"));
429+
430+
await expect(startAuthorizationCodeFlow()).rejects.toThrow("no browser");
431+
432+
expect(loopback.close).toHaveBeenCalled();
433+
});
434+
435+
it("states the listener's own limit while waiting", async () => {
436+
const log = vi.spyOn(console, "log").mockImplementation(() => {});
437+
vi.mocked(startLoopback).mockResolvedValueOnce({
438+
...loopbackStub("7 minutes"),
439+
result: Promise.reject(new Error("stop here")),
440+
});
441+
442+
await expect(startAuthorizationCodeFlow()).rejects.toThrow("stop here");
443+
444+
expect(log).toHaveBeenCalledWith(expect.stringContaining("up to 7 minutes"));
445+
});
446+
});
447+
414448
describe("startAuthorizationCodeFlow persistence", () => {
415449
it("overwrites the OAuth block on fresh login (no inherited refresh_token)", async () => {
416450
// Pre-seed a prior session whose refresh_token must NOT leak into

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

Lines changed: 23 additions & 22 deletions
Original file line numberDiff line numberDiff line change
@@ -80,7 +80,7 @@ export interface AuthorizeFlowOptions {
8080
scope?: string;
8181
/** Inject a custom fetch (used by tests). */
8282
fetchImpl?: typeof fetch;
83-
/** Override timeout in ms (default 120s). */
83+
/** Override timeout in ms (default 60 minutes). */
8484
timeoutMs?: number;
8585
}
8686

@@ -143,31 +143,32 @@ export async function startAuthorizationCodeFlow(
143143
const state = generateState();
144144

145145
const loopback = await startLoopback({ state, timeoutMs: opts.timeoutMs });
146-
const authorizeUrl = buildAuthorizeUrl({
147-
clientId,
148-
redirectUri: loopback.redirectUri,
149-
scope,
150-
state,
151-
challenge: pkce.challenge,
152-
});
153-
154-
// Print the host+path only (no state / code_challenge) so live
155-
// values can't leak into scrollback / CI logs during the 120s window.
156-
console.log(`Opening browser to ${c.dim(authorizeHost(authorizeUrl))} ...`);
157-
const { opened } = await openBrowser(authorizeUrl);
158-
if (!opened) {
159-
// openBrowser already printed the manual URL; surface it as the
160-
// last on-screen instruction so it isn't buried above "Waiting…".
161-
console.log(c.dim("(open the URL above to continue)"));
162-
}
163-
console.log(`Waiting for callback on ${c.accent(loopback.redirectUri)} ...`);
164-
165146
let codeResult;
166147
try {
148+
const authorizeUrl = buildAuthorizeUrl({
149+
clientId,
150+
redirectUri: loopback.redirectUri,
151+
scope,
152+
state,
153+
challenge: pkce.challenge,
154+
});
155+
156+
// Print the host+path only (no state / code_challenge) so live
157+
// values can't leak into scrollback / CI logs during the wait.
158+
console.log(`Opening browser to ${c.dim(authorizeHost(authorizeUrl))} ...`);
159+
const { opened } = await openBrowser(authorizeUrl);
160+
if (!opened) {
161+
// openBrowser already printed the manual URL; surface it as the
162+
// last on-screen instruction so it isn't buried above "Waiting…".
163+
console.log(c.dim("(open the URL above to continue)"));
164+
}
165+
console.log(
166+
`Waiting for callback on ${c.accent(loopback.redirectUri)} (up to ${loopback.timeoutLabel}, Ctrl+C to cancel) ...`,
167+
);
168+
167169
codeResult = await loopback.result;
168-
} catch (err) {
170+
} finally {
169171
await loopback.close().catch(() => {});
170-
throw err;
171172
}
172173

173174
const tokens = await exchangeCodeForTokens({

‎packages/cli/src/commands/auth/login.test.ts‎

Lines changed: 38 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -3,7 +3,7 @@ import { join } from "node:path";
33
import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";
44
import { readStore, writeStore } from "../../auth/store.js";
55
import { setupTempAuthEnv, type EnvFixture } from "../../auth/_test-utils.js";
6-
import { CliRuntimeError } from "../../utils/commandResult.js";
6+
import { CliRuntimeError, registerRootExitRequester } from "../../utils/commandResult.js";
77

88
// heygenUserId("alice"): the sha256-derived UUID the web app and Desktop also use.
99
const ALICE_USER_ID = "2bd806c9-7f0e-50af-9a1f-c3328fa763a9";
@@ -391,6 +391,43 @@ describe("auth login", () => {
391391
expect(telemetry.trackAuthLoginCompleted).toHaveBeenCalledWith("oauth", "[email protected]");
392392
});
393393

394+
it("tells a timed-out browser login how to recover", async () => {
395+
browserAuth.start.mockRejectedValueOnce(new Error("OAuth callback timed out after 60 minutes"));
396+
await expect(runCommand({})).rejects.toThrow();
397+
expect(console.error).toHaveBeenCalledWith(
398+
expect.stringContaining("Run `hyperframes auth login` again"),
399+
);
400+
expect(telemetry.trackAuthLoginFailed).toHaveBeenCalledWith("oauth", "flow_timeout");
401+
});
402+
403+
it("does not offer the recovery line for other browser login failures", async () => {
404+
browserAuth.start.mockRejectedValueOnce(
405+
new Error("OAuth state mismatch — possible CSRF, aborting."),
406+
);
407+
await expect(runCommand({})).rejects.toThrow();
408+
expect(console.error).not.toHaveBeenCalledWith(
409+
expect.stringContaining("hyperframes auth login"),
410+
);
411+
expect(telemetry.trackAuthLoginFailed).toHaveBeenCalledWith("oauth", "flow_error");
412+
});
413+
414+
it("records Ctrl+C during the browser wait as aborted and exits", async () => {
415+
const exit = vi.fn();
416+
registerRootExitRequester(exit);
417+
const before = process.listeners("SIGINT");
418+
browserAuth.start.mockImplementationOnce(async () => {
419+
const added = process.listeners("SIGINT").filter((listener) => !before.includes(listener));
420+
added[0]?.("SIGINT");
421+
throw new Error("interrupted");
422+
});
423+
424+
await expect(runCommand({})).rejects.toThrow();
425+
426+
expect(telemetry.trackAuthLoginFailed).toHaveBeenCalledWith("oauth", "aborted");
427+
expect(exit).toHaveBeenCalledWith(130);
428+
expect(process.listeners("SIGINT")).toEqual(before);
429+
});
430+
394431
it("refuses device authorization in CI", async () => {
395432
process.env["CI"] = "true";
396433
await expect(runCommand({ device: true })).rejects.toThrow(/Invalid command usage/);

‎packages/cli/src/commands/auth/login.ts‎

Lines changed: 14 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -1,4 +1,4 @@
1-
import { failCommand, failUsage } from "../../utils/commandResult.js";
1+
import { failCommand, failUsage, requestCliExit } from "../../utils/commandResult.js";
22
import { envFlagEnabled, isAttendedTerminal, isCI } from "../../utils/attendedTerminal.js";
33
import { isAgentDriven } from "../../telemetry/agent_runtime.js";
44
/**
@@ -221,6 +221,12 @@ async function runOAuthLogin(): Promise<void> {
221221
const { trackAuthLoginStarted, trackAuthLoginFailed } = await import("../../telemetry/index.js");
222222
trackAuthLoginStarted("oauth");
223223

224+
const recordCancel = (): void => {
225+
trackAuthLoginFailed("oauth", "aborted");
226+
requestCliExit(130);
227+
};
228+
process.once("SIGINT", recordCancel);
229+
224230
let tokens;
225231
try {
226232
({ tokens } = await startAuthorizationCodeFlow());
@@ -230,9 +236,15 @@ async function runOAuthLogin(): Promise<void> {
230236
// the user never completes the browser step (closed the tab / walked away).
231237
// That is the dominant non-error dropout, so split it from real failures
232238
// (IdP misconfig, network) instead of lumping everything as flow_error.
233-
trackAuthLoginFailed("oauth", /timed out/i.test(message) ? "flow_timeout" : "flow_error");
239+
const timedOut = /timed out/i.test(message);
240+
trackAuthLoginFailed("oauth", timedOut ? "flow_timeout" : "flow_error");
234241
console.error(c.error(`Sign-in failed: ${message}`));
242+
if (timedOut) {
243+
console.error("Run `hyperframes auth login` again.");
244+
}
235245
failCommand();
246+
} finally {
247+
process.off("SIGINT", recordCancel);
236248
}
237249

238250
await reportIdentity(issuedCredential(tokens));

‎packages/cli/src/telemetry/events.ts‎

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -859,7 +859,7 @@ export type AuthLoginFailureReason =
859859
| "flow_timeout" // OAuth callback wait elapsed (user closed the tab / walked away)
860860
| "rejected" // backend rejected the supplied API key (401)
861861
| "invalid_input" // key was empty, header-unsafe, or too short
862-
| "aborted"; // prompt cancelled, or no key arrived on stdin before timeout
862+
| "aborted"; // prompt or browser wait cancelled, or no key arrived on stdin before timeout
863863

864864
export function trackAuthLoginStarted(method: AuthLoginMethod, distinctId?: string): void {
865865
trackEvent("auth_login_started", { method }, distinctId);

0 commit comments

Comments
 (0)