diff --git a/packages/cli/src/auth/loopback.test.ts b/packages/cli/src/auth/loopback.test.ts index 76d63c7705..4fb51dbc68 100644 --- a/packages/cli/src/auth/loopback.test.ts +++ b/packages/cli/src/auth/loopback.test.ts @@ -41,12 +41,25 @@ describe("auth/loopback", () => { await expect(handle.result).rejects.toThrow(args.pattern); } - it("rejects when state does not match", async () => { - await expectRejection({ - expectedState: "expected", - query: "code=abc&state=wrong", - pattern: /state mismatch/i, - }); + it.each([ + ["a wrong state", "code=abc&state=wrong"], + ["no state", "code=abc"], + ["an error and no state", "error=access_denied&error_description=denied"], + ["an error and a wrong state", "error=server_error&state=wrong"], + ])("answers a callback with %s with a 400 and keeps waiting", async (_label, query) => { + const handle = await startLoopback({ state: "expected", timeoutMs: 5_000 }); + active = handle; + const settled = vi.fn(); + handle.result.then(settled, settled); + + const res = await fetch(`${handle.redirectUri}?${query}`); + expect(res.status).toBe(400); + expect(await res.text()).toContain("Your terminal is still waiting"); + await new Promise((resolve) => setTimeout(resolve, 20)); + expect(settled).not.toHaveBeenCalled(); + + await fetch(`${handle.redirectUri}?code=the_code&state=expected`); + await expect(handle.result).resolves.toMatchObject({ code: "the_code" }); }); it("rejects when the IdP returns an error", async () => { @@ -57,6 +70,19 @@ describe("auth/loopback", () => { }); }); + it("shows control characters in the IdP error as visible escapes", async () => { + const handle = await startLoopback({ state: "s", timeoutMs: 5_000 }); + active = handle; + const failed = handle.result.catch((error: Error) => error.message); + await fetch( + `${handle.redirectUri}?error=server%1B%5D0%3Bx%07&error_description=a%0D%0Ab%1B%5B2J&state=s`, + ); + + expect(await failed).toBe( + "OAuth authorize returned error: server\\x1b]0;x\\x07 — a\\x0d\\x0ab\\x1b[2J", + ); + }); + async function pageFor(query: string): Promise { const handle = await startLoopback({ state: "s", timeoutMs: 5_000 }); active = handle; diff --git a/packages/cli/src/auth/loopback.ts b/packages/cli/src/auth/loopback.ts index f145230f77..0440ad7873 100644 --- a/packages/cli/src/auth/loopback.ts +++ b/packages/cli/src/auth/loopback.ts @@ -10,18 +10,23 @@ * redirect URI's port is just a placeholder — the actual port the * server lands on is what matters at runtime. * - * Times out after 60 minutes. Validates `state` matches the value we - * generated. Renders a small "you can close this window" page back - * to the browser before shutting down. + * Times out after 60 minutes. Only a request with our `state` ends the + * flow; others get a 400 and the server keeps waiting. Renders a small + * "you can close this window" page back to the browser before shutting down. */ import { timingSafeEqual } from "node:crypto"; import { createServer, type IncomingMessage, type Server, type ServerResponse } from "node:http"; import { AddressInfo } from "node:net"; +import { terminalText } from "@hyperframes/core"; import { connectedPage, failurePage } from "./callbackPage.js"; +// Shown for a callback from another sign-in, such as an older tab; the terminal keeps waiting. +const STALE_SIGN_IN = + "This page is from a different sign-in. Your terminal is still waiting: finish signing in from the newest sign-in tab."; + export interface LoopbackOptions { - /** Expected `state` value — flow fails if it doesn't match. */ + /** Expected `state` value — a callback without it is answered 400 and ignored. */ state: string; /** Timeout in ms (default 60 minutes). */ timeoutMs?: number; @@ -135,18 +140,18 @@ function handleRequest( } const params = url.searchParams; + const state = params.get("state"); + if (!state || !stateMatches(state, expectedState)) { + respond(res, 400, failurePage("invalid_state", STALE_SIGN_IN)); + return; + } + const error = params.get("error"); if (error) { const desc = params.get("error_description") ?? ""; respond(res, 400, failurePage(error, desc)); - rejectResult(new Error(`OAuth authorize returned error: ${error}${desc ? ` — ${desc}` : ""}`)); - return; - } - - const state = params.get("state"); - if (!state || !stateMatches(state, expectedState)) { - respond(res, 400, failurePage("invalid_state", "State parameter did not match.")); - rejectResult(new Error("OAuth state mismatch — possible CSRF, aborting.")); + const shown = `${terminalText(error)}${desc ? ` — ${terminalText(desc)}` : ""}`; + rejectResult(new Error(`OAuth authorize returned error: ${shown}`)); return; } diff --git a/packages/cli/src/cloud/fontPreflight.test.ts b/packages/cli/src/cloud/fontPreflight.test.ts index 157df0daa1..16ac8c4497 100644 --- a/packages/cli/src/cloud/fontPreflight.test.ts +++ b/packages/cli/src/cloud/fontPreflight.test.ts @@ -93,4 +93,11 @@ describe("describeSwappedFonts", () => { "Zapfino is not on this computer, so it renders in the next font of its stack (or the default font), as a local render does.", ); }); + + it("shows control characters in a font name as visible escapes and keeps its look-alike", () => { + expect(describeSwappedFonts(["PingFang SC\n", `Brand${String.fromCharCode(27)}[2J`])).toBe( + "PingFang SC\\x0a is not on this computer, so it renders in the next font of its stack (or the default font), as a local render does; Noto Sans SC is a free look-alike you can use instead.\n" + + "Brand\\x1b[2J is not on this computer, so it renders in the next font of its stack (or the default font), as a local render does.", + ); + }); }); diff --git a/packages/cli/src/cloud/fontPreflight.ts b/packages/cli/src/cloud/fontPreflight.ts index 1797e316fd..01f3fc7c72 100644 --- a/packages/cli/src/cloud/fontPreflight.ts +++ b/packages/cli/src/cloud/fontPreflight.ts @@ -1,4 +1,5 @@ // Carries the system fonts a project uses inside its zip, as the cloud has no copy of them. +import { terminalText } from "@hyperframes/core"; import { bundleWithLocalizedFonts } from "../utils/bundleWithLocalizedFonts.js"; import { loadProducer } from "../utils/producer.js"; import { readStaged, type StagedFile } from "../utils/publishProject.js"; @@ -128,7 +129,7 @@ export function describeSwappedFonts(families: readonly string[]): string { return families .map((family) => { const swap = lookAlikeFor(family); - return `${family} is not on this computer, so it renders in the next font of its stack (or the default font), as a local render does${ + return `${terminalText(family)} is not on this computer, so it renders in the next font of its stack (or the default font), as a local render does${ swap ? `; ${swap} is a free look-alike you can use instead` : "" }.`; }) diff --git a/packages/cli/src/commands/auth/login.test.ts b/packages/cli/src/commands/auth/login.test.ts index 39d6a4efab..1a4338ce99 100644 --- a/packages/cli/src/commands/auth/login.test.ts +++ b/packages/cli/src/commands/auth/login.test.ts @@ -412,6 +412,19 @@ describe("auth login", () => { expect(telemetry.trackAuthLoginFailed).toHaveBeenCalledWith("oauth", "flow_error"); }); + it("prints a browser login failure with control characters as visible escapes", async () => { + const esc = String.fromCharCode(27); + browserAuth.start.mockRejectedValueOnce(new Error(`denied ${esc}]0;x\x07 by\r\nproxy`)); + await expect(runCommand({})).rejects.toThrow(); + const printed = vi + .mocked(console.error) + .mock.calls.map((call) => call.join(" ")) + .join("\n"); + + expect(printed.replace(new RegExp(`${esc}\\[[0-9;]*m`, "g"), "")).not.toContain(esc); + expect(printed).toContain("denied \\x1b]0;x\\x07 by\\x0d\nproxy"); + }); + it("records Ctrl+C during the browser wait as aborted and exits", async () => { const exit = vi.fn(); registerRootExitRequester(exit); diff --git a/packages/cli/src/commands/auth/login.ts b/packages/cli/src/commands/auth/login.ts index 36f0edb2aa..1066d0ffe8 100644 --- a/packages/cli/src/commands/auth/login.ts +++ b/packages/cli/src/commands/auth/login.ts @@ -49,6 +49,7 @@ import { } from "../../auth/index.js"; import { telemetryIdentity } from "../../auth/telemetryIdentity.js"; import { c } from "../../ui/colors.js"; +import { terminalLines } from "@hyperframes/core"; const STDIN_TIMEOUT_MS = 30_000; // Smallest plausible length for a real API key. We don't validate the @@ -215,7 +216,7 @@ async function runOAuthLogin(): Promise { // (IdP misconfig, network) instead of lumping everything as flow_error. const timedOut = /timed out/i.test(message); trackAuthLoginFailed("oauth", timedOut ? "flow_timeout" : "flow_error"); - console.error(c.error(`Sign-in failed: ${message}`)); + console.error(c.error(`Sign-in failed: ${terminalLines(message)}`)); if (timedOut) { console.error("Run `hyperframes auth login` again."); } diff --git a/packages/cli/src/commands/batchRender.test.ts b/packages/cli/src/commands/batchRender.test.ts index a783469f96..6b74ff92d5 100644 --- a/packages/cli/src/commands/batchRender.test.ts +++ b/packages/cli/src/commands/batchRender.test.ts @@ -339,6 +339,38 @@ describe("runBatchRender", () => { }, ); + it("prints a row's render error with control characters as visible escapes", async () => { + const esc = String.fromCharCode(27); + const prepared = prepareBatchRender({ + batchPath: writeJson("rows.json", '[{"name":"Alice"}]'), + outputTemplate: join(tmpDir, "renders/{name}.mp4"), + indexPath: writeIndex(), + strictVariables: false, + quiet: true, + json: false, + }); + const message = `Composition is empty: ${esc}]0;x\x07scene.html\r\nsecond line`; + const log = vi.spyOn(console, "log").mockImplementation(() => {}); + + const manifest = await runBatchRender({ + prepared, + concurrency: 1, + failFast: false, + quiet: false, + json: false, + renderOne: async () => { + throw new Error(message); + }, + }); + const human = log.mock.calls.map((call) => call.join(" ")).join("\n"); + + expect(human.replace(new RegExp(`${esc}\\[[0-9;]*m`, "g"), "")).not.toContain(esc); + expect(human).toContain( + "Row 0 failed: Composition is empty: \\x1b]0;x\\x07scene.html\\x0d\nsecond line", + ); + expect(manifest.rows[0]?.error).toBe(message); + }); + it("renders from manifest.json when the generated manifest has a separate directory", async () => { const original = '[{"name":"Alice"},{"name":"Bob"}]'; const batchPath = writeJson("manifest.json", original); diff --git a/packages/cli/src/commands/batchRender.ts b/packages/cli/src/commands/batchRender.ts index 5bc50fcf45..b428c4693d 100644 --- a/packages/cli/src/commands/batchRender.ts +++ b/packages/cli/src/commands/batchRender.ts @@ -4,7 +4,7 @@ import { makeOutputFolder } from "../utils/outputFolder.js"; import { readJsonFileText } from "../utils/jsonFlag.js"; import { dirname, isAbsolute, join, relative, resolve, sep } from "node:path"; import { c } from "../ui/colors.js"; -import { terminalText } from "@hyperframes/core"; +import { terminalLines, terminalText } from "@hyperframes/core"; import { errorBox } from "../ui/format.js"; import { normalizeErrorMessage as errorMessage } from "../utils/errorMessage.js"; import type { ReferenceBackground, ReferenceBackgroundResult } from "@hyperframes/producer"; @@ -385,7 +385,7 @@ async function renderBatchRow( manifestRow.completedAt = new Date().toISOString(); writeManifest(manifest); if (!options.quiet && !options.json) { - console.log(c.error(` Row ${row.index} failed: ${manifestRow.error}`)); + console.log(c.error(` Row ${row.index} failed: ${terminalLines(manifestRow.error)}`)); } return false; } @@ -416,7 +416,7 @@ export async function runBatchRender(options: RunBatchRenderOptions): Promise ({ + offloaded: undefined as OffloadedMedia[] | undefined, + swappedFonts: undefined as string[] | undefined, +})); + +vi.mock("../../cloud/offload.js", async (importOriginal) => { + const actual = await importOriginal(); + return { + ...actual, + offloadHeavyMedia: async (...args: Parameters) => { + if (!fixture.offloaded) return actual.offloadHeavyMedia(...args); + for (const item of fixture.offloaded) args[2].onFile?.(item); + return fixture.offloaded; + }, + }; +}); + +vi.mock("../../cloud/fontPreflight.js", async (importOriginal) => { + const actual = await importOriginal(); + return { + ...actual, + embedSystemFonts: async (...args: Parameters) => + fixture.swappedFonts ?? actual.embedSystemFonts(...args), + }; +}); + import render from "./render.js"; import { consumeCommandResult } from "../../utils/commandResult.js"; @@ -27,6 +55,8 @@ beforeEach(() => { }); afterEach(() => { + fixture.offloaded = undefined; + fixture.swappedFonts = undefined; vi.unstubAllEnvs(); vi.unstubAllGlobals(); vi.restoreAllMocks(); @@ -66,6 +96,33 @@ describe.skipIf(process.platform === "win32")("cloud render on a terminal", () = expect(human).toContain(".env.\\x1b[2J"); }); + it("prints archive file paths with control characters as visible escapes", async () => { + vi.stubGlobal("fetch", vi.fn()); + writeFileSync(join(dir, `clip${esc}[2J.txt`), "text"); + fixture.offloaded = [ + { path: `media/a${esc}]0;x.mp4`, size_bytes: 10, action: "upload" }, + { path: `media/b${esc}[1A.mp4`, size_bytes: 10, action: "upload", kept_in_archive: true }, + ]; + + const human = await humanOutput([dir, "--dry-run"]); + + expect(human.replace(colors, "")).not.toContain(esc); + expect(human).toContain("media/a\\x1b]0;x.mp4 · would upload"); + expect(human).toContain("media/b\\x1b[1A.mp4 also stays in the zip"); + expect(human).toContain("Largest included files:"); + expect(human).toContain("clip\\x1b[2J.txt"); + }); + + it("prints swapped font names with control characters as visible escapes", async () => { + vi.stubGlobal("fetch", vi.fn()); + fixture.swappedFonts = [`Brand${esc}[2J\nSans`]; + + const human = await humanOutput([dir, "--dry-run"]); + + expect(human.replace(colors, "")).not.toContain(esc); + expect(human).toContain("Brand\\x1b[2J\\x0aSans is not on this computer"); + }); + it("prints the upload progress name with control characters as visible escapes", async () => { // The first upload attempt fails, so the retry prints a progress line. let uploads = 0; diff --git a/packages/cli/src/commands/cloud/render.test.ts b/packages/cli/src/commands/cloud/render.test.ts index 51b0a4e437..690e969dc6 100644 --- a/packages/cli/src/commands/cloud/render.test.ts +++ b/packages/cli/src/commands/cloud/render.test.ts @@ -282,6 +282,21 @@ describe("assertArchiveFits", () => { "data/scan.tiff", ); }); + + it("names the largest files with control characters, line feeds included, as visible escapes", () => { + const esc = String.fromCharCode(27); + const errors = vi.mocked(console.error); + errors.mockClear(); + expect(() => + assertArchiveFits(200 * 1024 * 1024 + 1, [ + { path: `a${esc}[2J\n 190.0 MB b.tiff`, size_bytes: 190 * 1024 * 1024 }, + ]), + ).toThrow(CliRuntimeError); + const printed = errors.mock.calls.flat().join("\n"); + + expect(printed.replace(new RegExp(`${esc}\\[[0-9;]*m`, "g"), "")).not.toContain(esc); + expect(printed).toContain("a\\x1b[2J\\x0a 190.0 MB b.tiff"); + }); }); describe("parseAspectRatioFlag", () => { diff --git a/packages/cli/src/commands/cloud/render.ts b/packages/cli/src/commands/cloud/render.ts index 85c084ea36..9e86388de0 100644 --- a/packages/cli/src/commands/cloud/render.ts +++ b/packages/cli/src/commands/cloud/render.ts @@ -631,7 +631,7 @@ export function parseAspectRatioFlag(raw: string | undefined): string | undefine function logDetection(asJson: boolean, message: string): void { if (asJson) return; - console.log(c.dim(` ${message}`)); + console.log(c.dim(` ${terminalText(message)}`)); } // fallow-ignore-next-line complexity @@ -870,7 +870,7 @@ async function offloadMedia( for (const item of offloaded.filter((entry) => entry.kept_in_archive)) { console.log( c.dim( - ` ${item.path} also stays in the zip: a script builds its path in a way that cannot be rewritten`, + ` ${terminalText(item.path)} also stays in the zip: a script builds its path in a way that cannot be rewritten`, ), ); } @@ -896,7 +896,7 @@ export function assertArchiveFits(sizeBytes: number, largestFiles: ArchiveFileSu errorBox( "Project too large for cloud render", `The zip is ${formatBytes(sizeBytes)} after moving media to HeyGen assets, over the ${formatBytes(DIRECT_UPLOAD_LIMIT_BYTES)} upload limit. Largest files left in it:\n${largestFiles - .map((file) => ` ${formatBytes(file.size_bytes).padStart(9)} ${file.path}`) + .map((file) => ` ${formatBytes(file.size_bytes).padStart(9)} ${terminalText(file.path)}`) .join("\n")}`, "Exclude files the render does not need with .hyperframesignore.", ); @@ -967,13 +967,15 @@ function describeOffload(item: OffloadedMedia, dryRun: boolean): string { : dryRun ? "would upload" : "uploaded"; - return `${formatBytes(item.size_bytes).padStart(9)} ${item.path} · ${verb}`; + return `${formatBytes(item.size_bytes).padStart(9)} ${terminalText(item.path)} · ${verb}`; } function reportLargestFiles(prepared: PreparedLocalArchive): void { console.log(c.dim(" Largest included files:")); for (const file of prepared.largestFiles) { - console.log(c.dim(` ${formatBytes(file.size_bytes).padStart(9)} ${file.path}`)); + console.log( + c.dim(` ${formatBytes(file.size_bytes).padStart(9)} ${terminalText(file.path)}`), + ); } console.log(c.dim(" Exclude verified-unneeded files with .hyperframesignore.")); } diff --git a/packages/cli/src/commands/publish.test.ts b/packages/cli/src/commands/publish.test.ts index 55bbd7d91f..2fca0ad861 100644 --- a/packages/cli/src/commands/publish.test.ts +++ b/packages/cli/src/commands/publish.test.ts @@ -136,6 +136,23 @@ describe("publish default-entry preflight", () => { expect(output).toContain("publish accepts project directories, not individual HTML files"); }); + // Windows refuses control characters in file names. + it.skipIf(process.platform === "win32")( + "prints the suggested composition path with control characters as visible escapes", + async () => { + const esc = String.fromCharCode(27); + const withoutColors = (text: string) => + text.replace(new RegExp(`${esc}\\[[0-9;]*m`, "g"), ""); + const nested = await runEntryMismatch(`compositions/a${esc}]0;x\x07b/index.html`); + const standalone = await runEntryMismatch(`compositions/c${esc}]0;x\x07d.html`); + + expect(withoutColors(nested)).not.toContain(esc); + expect(nested).toContain("hyperframes publish /compositions/a\\x1b]0;x\\x07b"); + expect(withoutColors(standalone)).not.toContain(esc); + expect(standalone).toContain("Move or mount compositions/c\\x1b]0;x\\x07d.html"); + }, + ); + it("prints the full finding on a default-entry-mismatch abort even without --lint-verbose", async () => { const output = await runEntryMismatch("compositions/brand/index.html"); @@ -292,6 +309,31 @@ describe("publish visibility messaging", () => { } }); + it("prints a publish failure with control characters as visible escapes", async () => { + const esc = String.fromCharCode(27); + const project = mkdtempSync(join(tmpdir(), "hf-publish-failure-")); + writeFileSync(join(project, "index.html"), VISIBLE_INDEX); + publishState.publish.mockReset(); + publishState.publish.mockRejectedValue(new Error(`Could not read a${esc}[2Jb.png\r\nsecond`)); + const lines: string[] = []; + const error = vi.spyOn(console, "error").mockImplementation((...parts: unknown[]) => { + lines.push(parts.map(String).join(" ")); + }); + try { + await captureLog(() => + publishCommand.run?.({ args: { dir: project, yes: true, proxy: false } } as never), + ); + consumeCommandResult(); + const printed = lines.join("\n"); + + expect(printed).not.toContain(esc); + expect(printed).toContain("Could not read a\\x1b[2Jb.png\\x0d\nsecond"); + } finally { + error.mockRestore(); + rmSync(project, { recursive: true, force: true }); + } + }); + // Windows refuses control characters in file names. it.skipIf(process.platform === "win32")( "prints a left-out file name with control characters as visible escapes", diff --git a/packages/cli/src/commands/publish.ts b/packages/cli/src/commands/publish.ts index 7b4fb5c9bd..ea7860a7c3 100644 --- a/packages/cli/src/commands/publish.ts +++ b/packages/cli/src/commands/publish.ts @@ -132,7 +132,7 @@ export default defineCommand({ console.log(c.error(" Aborting publish because the default index.html entry is blank.")); if (candidate && posix.basename(candidate) === "index.html") { const candidateDir = posix.dirname(candidate); - const target = `/${candidateDir}`; + const target = `/${terminalText(candidateDir)}`; console.log( c.dim( ` Move or mount the authored file, or publish its directory directly: hyperframes publish ${target}. Only use the directory form when its assets are self-contained under that directory; otherwise mount it from the project root.`, @@ -141,7 +141,7 @@ export default defineCommand({ } else if (candidate) { console.log( c.dim( - ` Move or mount ${candidate} as a project index.html before publishing; publish accepts project directories, not individual HTML files.`, + ` Move or mount ${terminalText(candidate)} as a project index.html before publishing; publish accepts project directories, not individual HTML files.`, ), ); } @@ -399,7 +399,7 @@ export default defineCommand({ } catch (err: unknown) { publishSpinner.stop(c.error("Publish failed")); console.error(); - console.error(` ${(err as Error).message}`); + console.error(` ${terminalLines((err as Error).message)}`); console.error(); setCommandExitCode(1); return; diff --git a/packages/cli/src/utils/variables.test.ts b/packages/cli/src/utils/variables.test.ts index 23c5ed34d8..d059cb6125 100644 --- a/packages/cli/src/utils/variables.test.ts +++ b/packages/cli/src/utils/variables.test.ts @@ -1,4 +1,4 @@ -import { afterEach, beforeAll, beforeEach, describe, expect, it } from "vitest"; +import { afterEach, beforeAll, beforeEach, describe, expect, it, vi } from "vitest"; describe("parseVariablesArg", () => { let parseVariablesArg: typeof import("./variables.js").parseVariablesArg; @@ -163,3 +163,33 @@ describe("validateVariablesAgainstProject", () => { ).toEqual([]); }); }); + +describe("reportVariableIssues", () => { + afterEach(() => { + vi.restoreAllMocks(); + }); + + it("prints declared ids and options with control characters as visible escapes", async () => { + const { reportVariableIssues } = await import("./variables.js"); + const esc = String.fromCharCode(27); + const log = vi.spyOn(console, "log").mockImplementation(() => {}); + + reportVariableIssues( + [ + { kind: "undeclared", variableId: `title${esc}]0;x\x07` }, + { + kind: "enum-out-of-range", + variableId: "tone", + allowed: [`calm\nVariable "x" is fine.`], + actual: "loud", + }, + ], + { strict: false }, + ); + const printed = log.mock.calls.map((call) => call.join(" ")).join("\n"); + + expect(printed.replace(new RegExp(`${esc}\\[[0-9;]*m`, "g"), "")).not.toContain(esc); + expect(printed).toContain('Variable "title\\x1b]0;x\\x07" is not declared'); + expect(printed).toContain('must be one of "calm\\x0aVariable "x" is fine."'); + }); +}); diff --git a/packages/cli/src/utils/variables.ts b/packages/cli/src/utils/variables.ts index ad764f52a0..a55a671a4c 100644 --- a/packages/cli/src/utils/variables.ts +++ b/packages/cli/src/utils/variables.ts @@ -17,6 +17,7 @@ import { readFileSync } from "node:fs"; import { extractCompositionMetadata, formatVariableValidationIssue, + terminalText, validateVariables, type VariableValidationIssue, } from "@hyperframes/core"; @@ -226,7 +227,7 @@ export function reportVariableIssues( ), ); for (const issue of issues) { - console.log(" " + c.dim(formatVariableValidationIssue(issue))); + console.log(" " + c.dim(terminalText(formatVariableValidationIssue(issue)))); } console.log(""); }