Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
38 changes: 32 additions & 6 deletions packages/cli/src/auth/loopback.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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 () => {
Expand All @@ -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<string> {
const handle = await startLoopback({ state: "s", timeoutMs: 5_000 });
active = handle;
Expand Down
29 changes: 17 additions & 12 deletions packages/cli/src/auth/loopback.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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;
Expand Down Expand Up @@ -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;
}

Expand Down
7 changes: 7 additions & 0 deletions packages/cli/src/cloud/fontPreflight.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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.",
);
});
});
3 changes: 2 additions & 1 deletion packages/cli/src/cloud/fontPreflight.ts
Original file line number Diff line number Diff line change
@@ -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";
Expand Down Expand Up @@ -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` : ""
}.`;
})
Expand Down
13 changes: 13 additions & 0 deletions packages/cli/src/commands/auth/login.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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);
Expand Down
3 changes: 2 additions & 1 deletion packages/cli/src/commands/auth/login.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down Expand Up @@ -215,7 +216,7 @@ async function runOAuthLogin(): Promise<void> {
// (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.");
}
Expand Down
32 changes: 32 additions & 0 deletions packages/cli/src/commands/batchRender.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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);
Expand Down
6 changes: 3 additions & 3 deletions packages/cli/src/commands/batchRender.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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";
Expand Down Expand Up @@ -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;
}
Expand Down Expand Up @@ -416,7 +416,7 @@ export async function runBatchRender(options: RunBatchRenderOptions): Promise<Ba
console.log(
c.accent("◆") +
` Batch rendering ${options.prepared.rows.length} rows` +
c.dim(` → ${options.prepared.manifestPath}`),
c.dim(` → ${terminalText(options.prepared.manifestPath)}`),
);
console.log(c.dim(` batch concurrency: ${options.concurrency}`));
console.log("");
Expand Down
57 changes: 57 additions & 0 deletions packages/cli/src/commands/cloud/render.terminal.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,34 @@ import { createServer } from "node:http";
import { tmpdir } from "node:os";
import { join } from "node:path";
import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";
import type { OffloadedMedia } from "../../cloud/offload.js";

const fixture = vi.hoisted(() => ({
offloaded: undefined as OffloadedMedia[] | undefined,
swappedFonts: undefined as string[] | undefined,
}));

vi.mock("../../cloud/offload.js", async (importOriginal) => {
const actual = await importOriginal<typeof import("../../cloud/offload.js")>();
return {
...actual,
offloadHeavyMedia: async (...args: Parameters<typeof actual.offloadHeavyMedia>) => {
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<typeof import("../../cloud/fontPreflight.js")>();
return {
...actual,
embedSystemFonts: async (...args: Parameters<typeof actual.embedSystemFonts>) =>
fixture.swappedFonts ?? actual.embedSystemFonts(...args),
};
});

import render from "./render.js";
import { consumeCommandResult } from "../../utils/commandResult.js";

Expand All @@ -27,6 +55,8 @@ beforeEach(() => {
});

afterEach(() => {
fixture.offloaded = undefined;
fixture.swappedFonts = undefined;
vi.unstubAllEnvs();
vi.unstubAllGlobals();
vi.restoreAllMocks();
Expand Down Expand Up @@ -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;
Expand Down
15 changes: 15 additions & 0 deletions packages/cli/src/commands/cloud/render.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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", () => {
Expand Down
12 changes: 7 additions & 5 deletions packages/cli/src/commands/cloud/render.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down Expand Up @@ -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`,
),
);
}
Expand All @@ -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.",
);
Expand Down Expand Up @@ -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."));
}
Expand Down
Loading
Loading