diff --git a/packages/cli/src/auth/browser.test.ts b/packages/cli/src/auth/browser.test.ts new file mode 100644 index 0000000000..ef9eb15898 --- /dev/null +++ b/packages/cli/src/auth/browser.test.ts @@ -0,0 +1,53 @@ +import { afterEach, beforeEach, describe, expect, it, vi } from "vitest"; +import { openBrowser } from "./browser.js"; + +const ESC = String.fromCharCode(27); +const ODD = `od${ESC}[2Jd\x07`; +const SHOWN = "od\\x1b[2Jd\\x07"; + +const openState = vi.hoisted(() => ({ fail: "" })); +vi.mock("open", () => ({ + default: async () => { + if (openState.fail) throw new Error(openState.fail); + }, +})); + +describe("openBrowser when the page has to be opened by hand", () => { + const lines: string[] = []; + const printed = (): string => lines.join("\n").replace(new RegExp(`${ESC}\\[[0-9;]*m`, "g"), ""); + + beforeEach(() => { + lines.length = 0; + openState.fail = ""; + vi.stubEnv("HF_BROWSER_LOG", ""); + vi.stubEnv("BROWSER", ""); + vi.stubEnv("HF_NO_BROWSER", ""); + vi.spyOn(console, "error").mockImplementation((...args: unknown[]) => { + lines.push(args.join(" ")); + }); + }); + + afterEach(() => { + vi.unstubAllEnvs(); + vi.restoreAllMocks(); + }); + + // fails without the fix: the address is printed as it arrived. + it("shows control characters in the address as text when auto-open is off", async () => { + vi.stubEnv("HF_NO_BROWSER", "1"); + expect(await openBrowser(`https://example.com/${ODD}`)).toEqual({ opened: false }); + expect(printed()).toContain(`https://example.com/${SHOWN}`); + expect(printed()).not.toContain(ESC); + expect(printed()).not.toContain("\x07"); + }); + + // fails without the fix: the reason and the address are printed as they arrived. + it("shows control characters in the reason and address as text when opening fails", async () => { + openState.fail = `no display ${ODD}`; + expect(await openBrowser(`https://example.com/${ODD}`)).toEqual({ opened: false }); + expect(printed()).toContain(`(no display ${SHOWN}).`); + expect(printed()).toContain(`https://example.com/${SHOWN}`); + expect(printed()).not.toContain(ESC); + expect(printed()).not.toContain("\x07"); + }); +}); diff --git a/packages/cli/src/auth/browser.ts b/packages/cli/src/auth/browser.ts index 517a6d7f9e..fb530567bd 100644 --- a/packages/cli/src/auth/browser.ts +++ b/packages/cli/src/auth/browser.ts @@ -5,6 +5,7 @@ */ import { appendFileSync } from "node:fs"; +import { terminalText } from "@hyperframes/core"; import { c } from "../ui/colors.js"; import { normalizeErrorMessage } from "../utils/errorMessage.js"; @@ -35,9 +36,9 @@ export async function openBrowser(url: string): Promise { function printManualInstructions(url: string, detail?: string): void { if (detail) { - console.error(c.warn(`Could not open browser automatically (${detail}).`)); + console.error(c.warn(`Could not open browser automatically (${terminalText(detail)}).`)); } else { console.error(c.warn("Browser auto-open is disabled.")); } - console.error(`Open this URL manually to continue:\n ${c.accent(url)}`); + console.error(`Open this URL manually to continue:\n ${c.accent(terminalText(url))}`); } diff --git a/packages/cli/src/commands/auth/login.test.ts b/packages/cli/src/commands/auth/login.test.ts index 1a4338ce99..24b5bd2a5a 100644 --- a/packages/cli/src/commands/auth/login.test.ts +++ b/packages/cli/src/commands/auth/login.test.ts @@ -15,8 +15,9 @@ const ALICE_USER_ID = "2bd806c9-7f0e-50af-9a1f-c3328fa763a9"; // - user: the /v3/users/me identity returned on success const verifyState = vi.hoisted( () => - ({ reject: false, user: { email: "alice@example.com" } }) as { + ({ reject: false, detail: "invalid token", user: { email: "alice@example.com" } }) as { reject: boolean; + detail: string; user: Record; }, ); @@ -72,7 +73,7 @@ vi.mock("../../auth/index.js", async (orig) => { async getCurrentUser(credential: { access_token?: string }): Promise> { if (verifyState.reject) { const { ErrUnauthenticated: rej } = await import("../../auth/errors.js"); - throw rej("invalid token"); + throw rej(verifyState.detail); } return (credential.access_token && usersByToken[credential.access_token]) || verifyState.user; } @@ -128,6 +129,7 @@ describe("auth login", () => { envFixture = await setupTempAuthEnv("hf-login-"); dir = envFixture.dir; verifyState.reject = false; + verifyState.detail = "invalid token"; verifyState.user = { email: "alice@example.com" }; deviceChallenge.verificationUriComplete = undefined; for (const token of Object.keys(usersByToken)) delete usersByToken[token]; @@ -460,4 +462,86 @@ describe("auth login", () => { await runCommand({ device: true }); expect(deviceAuth.start).toHaveBeenCalledOnce(); }); + + describe("lines printed for people", () => { + const ESC = String.fromCharCode(27); + const ODD = `od${ESC}[2Jd\x07`; + const SHOWN = "od\\x1b[2Jd\\x07"; + const printed = (fn: typeof console.log): string => + vi + .mocked(fn) + .mock.calls.map((call) => call.join(" ")) + .join("\n") + .replace(new RegExp(`${ESC}\\[[0-9;]*m`, "g"), ""); + const expectShown = (fn: typeof console.log, lead: string): void => { + const text = printed(fn); + expect(text).toContain(lead); + expect(text).toContain(SHOWN); + expect(text).not.toContain(ESC); + expect(text).not.toContain("\x07"); + }; + + // fails without the fix: the address and the code reach the terminal as they arrived. + it("shows control characters in the device address and code as text", async () => { + deviceAuth.start.mockImplementationOnce(async (options) => { + options?.onChallenge?.({ verificationUri: `https://example.com/${ODD}`, userCode: ODD }); + return { access_token: "device-at", refresh_token: "device-rt", token_type: "Bearer" }; + }); + await runCommand({ device: true }); + expectShown(console.log, "Open https://example.com/"); + expect(printed(console.log)).toContain(`Enter code ${SHOWN}.`); + }); + + // fails without the fix: the raw message is printed. + it("shows control characters in a failed device authorization as text", async () => { + deviceAuth.start.mockRejectedValueOnce(new Error(`refused ${ODD}`)); + await expect(runCommand({ device: true })).rejects.toThrow(CliRuntimeError); + expectShown(console.error, "refused "); + }); + + // fails without the fix: the raw reason is printed. + it("shows control characters in an unverified device session's reason as text", async () => { + verifyState.reject = true; + verifyState.detail = ODD; + await expect(runCommand({ device: true })).rejects.toThrow(CliRuntimeError); + expectShown(console.error, "no credential was saved."); + }); + + // fails without the fix: the raw reason is printed. + it("shows control characters in an unsaved device session's reason as text", async () => { + deviceAuth.persist.mockRejectedValueOnce(new Error(`disk ${ODD}`)); + await expect(runCommand({ device: true })).rejects.toThrow(CliRuntimeError); + expectShown(console.error, "it was revoked. disk "); + }); + + // fails without the fix: the account name is printed as it arrived. + it.each([ + ["device", { device: true }, "Signed in as "], + ["browser", {}, "Signed in as "], + ["API key", { "api-key": "hg_goodkey456" }, "Authenticated as "], + ])( + "shows control characters in the %s sign-in's account name as text", + async (_, args, lead) => { + verifyState.user = { email: `${ODD}@example.com` }; + await runCommand(args); + expectShown(console.log, `${lead}${SHOWN}@example.com.`); + }, + ); + + // fails without the fix: the raw reason is printed. + it("shows control characters in a failed identity check after browser sign-in as text", async () => { + verifyState.reject = true; + verifyState.detail = ODD; + await runCommand({}); + expectShown(console.error, "Identity check failed (transient):"); + }); + + // fails without the fix: the raw reason is printed. + it("shows control characters in a rejected API key's reason as text", async () => { + verifyState.reject = true; + verifyState.detail = ODD; + await expect(runLogin("hg_badkey123")).rejects.toThrow(CliRuntimeError); + expectShown(console.error, "HeyGen rejected the API key."); + }); + }); }); diff --git a/packages/cli/src/commands/auth/login.ts b/packages/cli/src/commands/auth/login.ts index 1066d0ffe8..554dd3163f 100644 --- a/packages/cli/src/commands/auth/login.ts +++ b/packages/cli/src/commands/auth/login.ts @@ -49,7 +49,7 @@ import { } from "../../auth/index.js"; import { telemetryIdentity } from "../../auth/telemetryIdentity.js"; import { c } from "../../ui/colors.js"; -import { terminalLines } from "@hyperframes/core"; +import { terminalLines, terminalText } from "@hyperframes/core"; const STDIN_TIMEOUT_MS = 30_000; // Smallest plausible length for a real API key. We don't validate the @@ -123,15 +123,17 @@ async function runDeviceLogin(): Promise { try { tokens = await startDeviceAuthorizationFlow({ onChallenge: ({ verificationUri, verificationUriComplete, userCode }) => { - console.log(`Open ${c.accent(verificationUriComplete ?? verificationUri)} in a browser.`); - if (!verificationUriComplete) console.log(`Enter code ${c.bold(userCode)}.`); + console.log( + `Open ${c.accent(terminalText(verificationUriComplete ?? verificationUri))} in a browser.`, + ); + if (!verificationUriComplete) console.log(`Enter code ${c.bold(terminalText(userCode))}.`); console.log(c.dim("Waiting for approval…")); }, }); } catch (err) { const message = (err as Error).message || "Device authorization failed."; trackAuthLoginFailed("device", /expired/i.test(message) ? "flow_timeout" : "flow_error"); - console.error(c.error(message)); + console.error(c.error(terminalLines(message))); failCommand(); } @@ -143,7 +145,7 @@ async function runDeviceLogin(): Promise { trackAuthLoginFailed("device", "rejected"); console.error( c.error( - `HeyGen could not verify the approved device session; no credential was saved. ${(err as Error).message}`, + `HeyGen could not verify the approved device session; no credential was saved. ${terminalLines((err as Error).message)}`, ), ); failCommand(); @@ -156,7 +158,7 @@ async function runDeviceLogin(): Promise { trackAuthLoginFailed("device", "flow_error"); console.error( c.error( - `Could not save the verified device session; it was revoked. ${(err as Error).message}`, + `Could not save the verified device session; it was revoked. ${terminalLines((err as Error).message)}`, ), ); failCommand(); @@ -166,7 +168,7 @@ async function runDeviceLogin(): Promise { if (who) identifyUser(who.distinctId, who.traits); trackAuthLoginCompleted("device", who?.distinctId); const identity = userDisplayName(toStoredUserInfo(user)) ?? "(unknown user)"; - console.log(c.success(`✓ Signed in as ${identity}.`)); + console.log(c.success(`✓ Signed in as ${terminalText(identity)}.`)); } // The tokens this login just issued, never a resolved credential: an env credential can outrank them. @@ -250,7 +252,7 @@ async function reportIdentity(credential: ReturnType): if (who) identifyUser(who.distinctId, who.traits); trackAuthLoginCompleted("oauth", who?.distinctId); const identity = userDisplayName(toStoredUserInfo(user)) ?? "(unknown user)"; - console.log(c.success(`✓ Signed in as ${identity}.`)); + console.log(c.success(`✓ Signed in as ${terminalText(identity)}.`)); } catch (err) { // Don't roll back — the OAuth tokens are valid on disk; this is a // transient verify-side issue. The credential is persisted and usable, so @@ -260,7 +262,9 @@ async function reportIdentity(credential: ReturnType): await clearUserInfoBestEffort(); trackAuthLoginCompleted("oauth"); console.error( - c.warn(`Signed in. Identity check failed (transient): ${(err as Error).message}`), + c.warn( + `Signed in. Identity check failed (transient): ${terminalLines((err as Error).message)}`, + ), ); } } @@ -291,7 +295,9 @@ async function persistUserInfo(user: UserInfo): Promise { await saveUserInfo(stored); } } catch (err) { - console.error(c.dim(`(warning: could not persist user info: ${(err as Error).message})`)); + console.error( + c.dim(`(warning: could not persist user info: ${terminalLines((err as Error).message)})`), + ); } } @@ -300,7 +306,9 @@ async function clearUserInfoBestEffort(): Promise { try { await clearUserInfo(); } catch (err) { - console.error(c.dim(`(warning: could not clear stale user info: ${(err as Error).message})`)); + console.error( + c.dim(`(warning: could not clear stale user info: ${terminalLines((err as Error).message)})`), + ); } } @@ -319,7 +327,7 @@ async function runApiKeyLogin(inlineKey: string): Promise { key = await collectApiKey(inlineKey); } catch (err) { trackAuthLoginFailed("api_key", "aborted"); - console.error(c.error((err as Error).message || "Sign-in aborted.")); + console.error(c.error(terminalLines((err as Error).message || "Sign-in aborted."))); failCommand(); } if (!key) { @@ -383,7 +391,7 @@ async function rollback(previous: Credentials): Promise { console.error(c.dim("Removed the rejected credential.")); } } catch (err) { - console.error(c.error(`Failed to roll back: ${(err as Error).message}`)); + console.error(c.error(`Failed to roll back: ${terminalLines((err as Error).message)}`)); } } @@ -403,13 +411,13 @@ async function verifyAndReport(key: string): Promise { // so `auth status` can show a recognizable identity. Best-effort. await persistUserInfo(user); const identity = userDisplayName(toStoredUserInfo(user)) ?? "(unknown user)"; - console.log(c.success(`✓ API key saved. Authenticated as ${identity}.`)); + console.log(c.success(`✓ API key saved. Authenticated as ${terminalText(identity)}.`)); return user; } catch (err) { if (isAuthError(err) && err.code === "UNAUTHENTICATED") { console.error( `${c.warn("HeyGen rejected the API key.")}\n` + - ` ${c.dim(err.message)}\n` + + ` ${c.dim(terminalLines(err.message))}\n` + `Run ${c.accent("hyperframes auth login --api-key")} again with a valid key.`, ); return null; diff --git a/packages/cli/src/commands/auth/logout.test.ts b/packages/cli/src/commands/auth/logout.test.ts index 8520421a42..5dbfeb508d 100644 --- a/packages/cli/src/commands/auth/logout.test.ts +++ b/packages/cli/src/commands/auth/logout.test.ts @@ -1,3 +1,4 @@ +import { join } from "node:path"; import { afterEach, beforeEach, expect, it, vi } from "vitest"; import { setupTempAuthEnv, type EnvFixture } from "../../auth/_test-utils.js"; @@ -29,3 +30,25 @@ it("requires an explicit confirmation without a terminal", async () => { (cmd.run as (ctx: { args: Record }) => Promise)({ args: {} }), ).rejects.toThrow("auth logout --yes"); }); + +// fails without the fix: the folder name is printed as it is on disk. +it.skipIf(process.platform === "win32")( + "shows control characters in the removed credential file's path as text", + async () => { + const ESC = String.fromCharCode(27); + process.env["HYPERFRAMES_CONFIG_DIR"] = join(envFixture.dir, `cfg od${ESC}[2Jd\x07`); + const cmd = (await import("./logout.js")).default; + await (cmd.run as (ctx: { args: Record }) => Promise)({ + args: { yes: true }, + }); + + const text = vi + .mocked(console.log) + .mock.calls.map((call) => call.join(" ")) + .join("\n") + .replace(new RegExp(`${ESC}\\[[0-9;]*m`, "g"), ""); + expect(text).toContain("cfg od\\x1b[2Jd\\x07"); + expect(text).not.toContain(ESC); + expect(text).not.toContain("\x07"); + }, +); diff --git a/packages/cli/src/commands/auth/logout.ts b/packages/cli/src/commands/auth/logout.ts index 62ab4ac0a2..372d95e3ff 100644 --- a/packages/cli/src/commands/auth/logout.ts +++ b/packages/cli/src/commands/auth/logout.ts @@ -1,3 +1,4 @@ +import { terminalText } from "@hyperframes/core"; import { isUnattended } from "../../utils/attendedTerminal.js"; import { CliUsageError, failCommand } from "../../utils/commandResult.js"; /** @@ -54,7 +55,7 @@ export default defineCommand({ return; } await deleteStore(); - console.log(c.success(`✓ Signed out. Removed ${credentialPath()}.`)); + console.log(c.success(`✓ Signed out. Removed ${terminalText(credentialPath())}.`)); }, }); diff --git a/packages/cli/src/commands/preview.missingBuild.test.ts b/packages/cli/src/commands/preview.missingBuild.test.ts new file mode 100644 index 0000000000..b1c93f0c92 --- /dev/null +++ b/packages/cli/src/commands/preview.missingBuild.test.ts @@ -0,0 +1,47 @@ +import { afterEach, describe, expect, it, vi } from "vitest"; +import { consumeCommandResult } from "../utils/commandResult.js"; +import { runEmbeddedMode } from "./preview.js"; + +const ESC = String.fromCharCode(27); +const ODD = `od${ESC}[2Jd\x07`; + +vi.mock("../utils/attendedTerminal.js", async (importOriginal) => ({ + ...(await importOriginal()), + isUnattended: () => false, +})); +vi.mock("@clack/prompts", async (importOriginal) => ({ + ...(await importOriginal()), + spinner: () => ({ start: vi.fn(), stop: vi.fn(), message: vi.fn() }), + intro: () => {}, +})); +vi.mock("../server/studioServer.js", () => ({ + resolveStudioBundle: () => ({ available: false, checkedPaths: [`/opt/${ODD}/studio`] }), + loadPreviewServerBuildSignature: async () => "test", + originForListeningAddress: () => undefined, + createStudioServer: () => { + throw new Error("the server is not started without a studio build"); + }, +})); + +describe("preview with no studio build", () => { + afterEach(() => { + consumeCommandResult(); + vi.restoreAllMocks(); + }); + + // fails without the fix: the folder name is printed as it is on disk. + it("shows control characters in the folders it looked in as text", async () => { + const lines: string[] = []; + vi.spyOn(console, "error").mockImplementation((...args: unknown[]) => { + lines.push(args.join(" ")); + }); + + await runEmbeddedMode("missing-build-project", 3057, { noOpen: true }); + + const text = lines.join("\n").replace(new RegExp(`${ESC}\\[[0-9;]*m`, "g"), ""); + expect(text).toContain("/opt/od\\x1b[2Jd\\x07/studio"); + expect(text).not.toContain(ESC); + expect(text).not.toContain("\x07"); + expect(consumeCommandResult().exitCode).toBe(1); + }); +}); diff --git a/packages/cli/src/commands/preview.ts b/packages/cli/src/commands/preview.ts index 28089ace0a..1b9ec3b78f 100644 --- a/packages/cli/src/commands/preview.ts +++ b/packages/cli/src/commands/preview.ts @@ -1351,8 +1351,8 @@ function printStudioSummary( const urls = studioSummaryUrls(projectName, serverUrl); console.log(); console.log(` ${c.dim("Project")} ${c.accent(terminalText(projectName))}`); - console.log(` ${c.dim("Studio")} ${c.accent(urls.studioUrl)}`); - console.log(` ${c.dim("Server")} ${c.accent(urls.serverUrl)}`); + console.log(` ${c.dim("Studio")} ${c.accent(terminalText(urls.studioUrl))}`); + console.log(` ${c.dim("Server")} ${c.accent(terminalText(urls.serverUrl))}`); const hint = desktopHint(projectDir, { preview: opts.preview }); if (hint) console.log(` ${c.dim("Desktop")} ${terminalText(hint)}`); console.log(); @@ -1478,7 +1478,7 @@ function attachStudioReadyHandler( reportPreviewFailure(true, "start", "preview-start-failed", err.message); } else { spinner.stop(c.error("Failed to start studio")); - console.error(c.dim(err.message)); + console.error(c.dim(terminalLines(err.message))); } }); } @@ -1650,7 +1650,7 @@ export async function runEmbeddedMode( console.error(); console.error(` ${c.dim("Could not find")} ${c.accent("index.html")} ${c.dim("in:")}`); for (const checkedPath of studioBundle.checkedPaths) { - console.error(` ${c.dim("-")} ${checkedPath}`); + console.error(` ${c.dim("-")} ${terminalText(checkedPath)}`); } console.error(); console.error(` ${c.dim("Rebuild the CLI package with")} ${c.accent("bun run build")}`);