From b72970cb4ac063a009f1560656a577ecf28f73ce Mon Sep 17 00:00:00 2001 From: Terence Cho Date: Fri, 6 Nov 2026 16:09:52 -0800 Subject: [PATCH] feat(cli): share rendered videos through unified reviews (#7135) --- bun.lock | 1 + docs/packages/cli.mdx | 64 ++++- packages/cli/package.json | 1 + packages/cli/src/cli.ts | 1 + packages/cli/src/commands/render.test.ts | 29 ++ packages/cli/src/commands/render.ts | 13 +- packages/cli/src/commands/share.ts | 149 ++++++++++ packages/cli/src/share/auth.test.ts | 63 +++++ packages/cli/src/share/auth.ts | 60 ++++ packages/cli/src/share/errors.ts | 37 +++ packages/cli/src/share/host.ts | 67 +++++ .../cli/src/share/render.lifecycle.test.ts | 61 +++++ packages/cli/src/share/render.test.ts | 44 +++ packages/cli/src/share/render.ts | 92 +++++++ packages/cli/src/share/service.test.ts | 259 ++++++++++++++++++ packages/cli/src/share/service.ts | 224 +++++++++++++++ packages/cli/src/share/uploadOrigins.test.ts | 90 ++++++ packages/cli/src/share/uploadOrigins.ts | 28 ++ .../src/utils/render-success-state.test.ts | 29 ++ .../cli/src/utils/render-success-state.ts | 10 +- packages/cli/tsup.config.ts | 1 + packages/share/src/reviewExport.mjs | 10 +- packages/share/tests/kernel.test.mjs | 50 +++- 23 files changed, 1363 insertions(+), 20 deletions(-) create mode 100644 packages/cli/src/commands/share.ts create mode 100644 packages/cli/src/share/auth.test.ts create mode 100644 packages/cli/src/share/auth.ts create mode 100644 packages/cli/src/share/errors.ts create mode 100644 packages/cli/src/share/host.ts create mode 100644 packages/cli/src/share/render.lifecycle.test.ts create mode 100644 packages/cli/src/share/render.test.ts create mode 100644 packages/cli/src/share/render.ts create mode 100644 packages/cli/src/share/service.test.ts create mode 100644 packages/cli/src/share/service.ts create mode 100644 packages/cli/src/share/uploadOrigins.test.ts create mode 100644 packages/cli/src/share/uploadOrigins.ts diff --git a/bun.lock b/bun.lock index 7477213746..63f04c1d8d 100644 --- a/bun.lock +++ b/bun.lock @@ -99,6 +99,7 @@ "@hyperframes/lint": "workspace:*", "@hyperframes/parsers": "workspace:*", "@hyperframes/producer": "workspace:*", + "@hyperframes/share": "workspace:*", "@hyperframes/studio": "workspace:*", "@hyperframes/studio-server": "workspace:*", "@types/css-tree": "^3.2.0", diff --git a/docs/packages/cli.mdx b/docs/packages/cli.mdx index 8595ee1889..1ecf0d80eb 100644 --- a/docs/packages/cli.mdx +++ b/docs/packages/cli.mdx @@ -26,7 +26,7 @@ npm install -g hyperframes | ------------------------ | -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | | Start a project | [`init`](#init), [`add`](#add), [`catalog`](#catalog) | | Bring in source material | [`capture`](#capture), [`media-use`](#media-use), [`transcribe`](#transcribe), [`tts`](#tts), [`remove-background`](#remove-background), [`media-treatment`](#media-treatment), [`beats`](#beats), [`audio`](#audio), [`normalize-audio`](#normalize-audio), [`models`](#models) | -| Look at it, or share it | [`preview`](#preview), [`present`](#present-and-play), [`play`](#present-and-play), [`publish`](#publish), [`open`](#open-and-catch-up), [`catch-up`](#open-and-catch-up) | +| Look at it, or share it | [`share`](#share), [`preview`](#preview), [`present`](#present-and-play), [`play`](#present-and-play), [`publish`](#publish), [`open`](#open-and-catch-up), [`catch-up`](#open-and-catch-up) | | Find problems | [`lint`](#lint), [`check`](#check), [`snapshot`](#snapshot), [`keyframes`](#keyframes), [`compare`](#compare-and-grade-compare), [`grade-compare`](#compare-and-grade-compare) | | Rebuild a video | [`reverse`](#reverse), [`measure`](#measure), [`diff`](#diff) | | Edit from the terminal | [`timeline`](#timeline), [`history`](#history) | @@ -119,9 +119,9 @@ vision keys, models, Vertex settings and timeout, and the telemetry opt-outs `HY other key in the file is ignored, and one line on stderr names them. **Flags, not prompts.** A missing required flag fails immediately with a usage -example rather than waiting for input. Two commands are interactive on a TTY: +example rather than waiting for input. These commands can ask questions on a TTY: `init` prompts for a project name and example unless you pass -`--non-interactive`, and `catalog --human-friendly` opens a picker. Nothing else +`--non-interactive`, `catalog --human-friendly` opens a picker, and `share` asks for a first-share audience. Nothing else prompts, apart from confirmations you can skip with `--yes` or `--no-confirm`. **Unattended runs never prompt.** A run is unattended when stdin or stdout is not @@ -3034,3 +3034,61 @@ Anything you leave out gets the default, so the file only needs your overrides. The capture engine. Use directly for custom frame capture pipelines. + + +## share + +Share a rendered MP4 for review, with the same project identity, access controls, +comments and version history as HyperFrames Desktop. Sign in with +`hyperframes auth login` first; API keys cannot own review projects. + +```bash +hyperframes share --public # Explicitly allow anyone with the link +hyperframes share --status --json # Read status; never upload local edits +hyperframes share --update # Render and upload the current project +hyperframes share --manage # Open web sharing settings +``` + +The first share requires an explicit audience: `--public`, `--team`, +`--invite-only`, or `--private`. In an attended terminal, `share` asks you to +choose. `--yes` suppresses questions but does not choose an audience. Available +audiences follow your workspace plan. `--space ` selects the owning workspace +on first share; later runs preserve it. + +Free workspaces retain up to **five shared projects**, across CLI and Desktop. +Adding versions uses the same project. Turning off its link does not free a slot; +remove a project in web management or upgrade when the workspace is full. +The server enforces the limit even when clients create projects simultaneously. + +Running `share` again returns the existing link without uploading edits. Use +`--update` to publish a new rendered version. The previous ready version remains +visible while an update processes. Interrupted first uploads can resume when +the source is unchanged; if it changed, explicitly use `--update`. If the +project's review or audience changes while rendering, check the current share +with `--status` before retrying. + +Completed renders accumulate in `.hyperframes/share-renders/`. To reclaim that +space, wait for uploads to finish and close any running share commands, then +remove that directory and `.hyperframes/share-render.json`. The next share or +update that needs a render will rebuild the cache. + +`--wait-seconds <1–1800>` controls how long the command waits for video +processing (default 300). A processing result is accepted, not playback-ready: +check `ready` and `state` in JSON before distributing a URL. `url` is only +returned for a ready share. Run `--status` to check again. Exit codes are 0 +for an accepted/read operation, 1 for failure, and 2 for invalid arguments. +A successful local render does not finish sharing: upload failures still return +a failure exit code. + +The standard production CLI includes exact trusted storage origins for review +videos and editable project sources; no upload configuration is required. +Development environments, custom API/OAuth endpoints or clients, and custom +storage setups must set `HYPERFRAMES_REVIEW_UPLOAD_ORIGINS` to the +comma-separated HTTPS origins provided by their deployment. Use exact origins +without paths or wildcards. This setting replaces the production defaults; +setting it to an empty string disables uploads. Defaults apply only with the +production environment and standard production API, OAuth token endpoint, and +OAuth client. Storage URLs outside the selected origins are rejected. + +Existing `/p/...` publications remain separate and reachable. Sharing does not +convert a legacy publication or change its URL, visibility or ownership. diff --git a/packages/cli/package.json b/packages/cli/package.json index 13437e9435..348b921367 100644 --- a/packages/cli/package.json +++ b/packages/cli/package.json @@ -84,6 +84,7 @@ "@hyperframes/lint": "workspace:*", "@hyperframes/parsers": "workspace:*", "@hyperframes/producer": "workspace:*", + "@hyperframes/share": "workspace:*", "@hyperframes/studio": "workspace:*", "@hyperframes/studio-server": "workspace:*", "@types/css-tree": "^3.2.0", diff --git a/packages/cli/src/cli.ts b/packages/cli/src/cli.ts index 8979e4c44f..649ae0f539 100644 --- a/packages/cli/src/cli.ts +++ b/packages/cli/src/cli.ts @@ -143,6 +143,7 @@ const commandLoaders = { present: () => import("./commands/present.js").then((m) => m.default), preview: () => assertStudioWorkspaceBuilt().then(() => import("./commands/preview.js").then((m) => m.default)), + share: () => import("./commands/share.js").then((m) => m.default), publish: () => import("./commands/publish.js").then((m) => m.default), open: () => import("./commands/open.js").then((m) => m.default), "catch-up": () => import("./commands/catch-up.js").then((m) => m.default), diff --git a/packages/cli/src/commands/render.test.ts b/packages/cli/src/commands/render.test.ts index f852c3b87b..bddcffae4d 100644 --- a/packages/cli/src/commands/render.test.ts +++ b/packages/cli/src/commands/render.test.ts @@ -1422,6 +1422,35 @@ describe("renderLocal browser GPU config", () => { expect(consumeCommandResult().exitCode).toBe(0); }); + it("does not finalize the host command or mask a later upload failure when embedded", async () => { + const success = await import("../utils/render-success-state.js"); + const lifecycle = await import("../utils/commandResult.js"); + const exit = vi.spyOn(lifecycle, "scheduleCliExit"); + success._resetRenderSuccessForTests(); + const uploadFailure = new Error("upload failed after render"); + try { + const share = async () => { + await renderLocal(PROJECT_DIR, "/tmp/out.mp4", { + fps: { num: 30, den: 1 }, + quality: "standard", + format: "mp4", + gpu: false, + browserGpuMode: "software", + hdrMode: "auto", + quiet: true, + embedded: true, + exitAfterComplete: true, + }); + throw uploadFailure; + }; + await expect(share()).rejects.toBe(uploadFailure); + expect(exit).not.toHaveBeenCalled(); + expect(success.isRunDelivered()).toBe(false); + } finally { + success._resetRenderSuccessForTests(); + } + }); + it("still completes the render when the output registry cannot be written", async () => { const project = mkdtempSync(join(tmpdir(), "hf-render-unrecorded-")); mkdirSync(join(project, ".hyperframes")); diff --git a/packages/cli/src/commands/render.ts b/packages/cli/src/commands/render.ts index 3f8d7fa44b..415faae61d 100644 --- a/packages/cli/src/commands/render.ts +++ b/packages/cli/src/commands/render.ts @@ -572,6 +572,7 @@ export interface RenderOptions { variables?: Record; entryFile?: string; exitAfterComplete?: boolean; + embedded?: boolean; /** Output resolution preset; see `resolveDeviceScaleFactor` for constraints. */ outputResolution?: CanvasResolution; /** Whether the resolution names a tier without fixing an orientation. */ @@ -944,7 +945,7 @@ async function renderDocker( // AND committed the artifact. Mirror renderLocal's post-success guarantee // so any late throw here (telemetry flush, feedback prompt) cannot flip // the exit code. - markRenderSucceeded(); + if (!options.embedded) markRenderSucceeded(); await runPostRenderStepAsync("recordRenderSuccess", () => recordRenderSuccess(projectDir, outputPath, "completed", capture).then(() => {}), ); @@ -986,7 +987,7 @@ async function renderDocker( runPostRenderStep("warnIfWebmAlphaDropped", () => warnIfWebmAlphaDropped(outputPath, options.format, options.quiet), ); - if (options.exitAfterComplete) scheduleCliExit(); + if (options.exitAfterComplete && !options.embedded) scheduleCliExit(); return { renderTimeMs: elapsed }; } @@ -1250,7 +1251,7 @@ async function executeLocalRender( // point on, ANY thrown teardown error must not be allowed to override // the exit code. Field signal ts=1784169760 / ts=1784171150 / ts=1784172467 // (win32/x64, CLI 0.7.58): valid MP4 on disk, exited 1 with no error print. - markRenderSucceeded(); + if (!options.embedded) markRenderSucceeded(); await runPostRenderStepAsync("recordRenderSuccess", () => recordRenderSuccess( projectDir, @@ -1296,7 +1297,7 @@ async function executeLocalRender( }), ); } - if (options.exitAfterComplete) scheduleCliExit(); + if (options.exitAfterComplete && !options.embedded) scheduleCliExit(); const durationMs = job.perfSummary ? Math.round(job.perfSummary.compositionDurationSeconds * 1000) : undefined; @@ -1345,7 +1346,7 @@ async function renderRange(input: { } catch (error: unknown) { handleRenderError(error, options, input.startTime, input.cpu, false, ""); } - markRenderSucceeded(); + if (!options.embedded) markRenderSucceeded(); const elapsed = Date.now() - input.startTime; input.cpu.stop(); printRenderComplete({ @@ -1356,7 +1357,7 @@ async function renderRange(input: { quiet: options.quiet, format: options.format, }); - if (options.exitAfterComplete) scheduleCliExit(); + if (options.exitAfterComplete && !options.embedded) scheduleCliExit(); return { renderTimeMs: elapsed, ...reference, diff --git a/packages/cli/src/commands/share.ts b/packages/cli/src/commands/share.ts new file mode 100644 index 0000000000..9735a0d411 --- /dev/null +++ b/packages/cli/src/commands/share.ts @@ -0,0 +1,149 @@ +import { defineCommand } from "../utils/defineCommand.js"; +import { resolveProjectOrThrow } from "../utils/project.js"; +import { CliUsageError, setCommandExitCode } from "../utils/commandResult.js"; +import { isUnattended } from "../utils/attendedTerminal.js"; +import * as prompts from "../ui/prompts.js"; +import { + createShareService, + type ShareAction, + type ShareState, + type ShareService, +} from "../share/service.js"; +import { shareError } from "../share/errors.js"; +import { jsonFailure } from "../utils/jsonError.js"; +import type { Example } from "./_examples.js"; + +export const examples: Example[] = [ + ["Create a review anyone with its link can open", "hyperframes share --public"], + ["Add the current video as a new version", "hyperframes share --update"], + ["Read the existing share without uploading edits", "hyperframes share --status --json"], + ["Open sharing settings on the web", "hyperframes share --manage"], +]; + +export default defineCommand({ + meta: { + name: "share", + description: "Share a rendered video for review, using the same sharing as Desktop", + }, + args: { + dir: { type: "positional", description: "Project directory", required: false }, + public: { + type: "boolean", + description: "Explicitly allow anyone with the link on first share", + }, + team: { type: "boolean", description: "First share with this workspace" }, + "invite-only": { type: "boolean", description: "First share with invited people only" }, + private: { type: "boolean", description: "First share with private access" }, + update: { + type: "boolean", + description: "Render and add a new video version to the existing share", + }, + status: { type: "boolean", description: "Read status without rendering or uploading" }, + manage: { type: "boolean", description: "Open this share's web management page" }, + space: { type: "string", description: "Owning workspace for a new share" }, + "wait-seconds": { + type: "string", + description: "Wait for processing (1–1800 seconds)", + default: "300", + }, + json: { type: "boolean", description: "Emit a machine-readable result" }, + yes: { + type: "boolean", + alias: "y", + description: "Do not prompt; an explicit first-share audience is still required", + }, + }, + async run({ args }) { + try { + const input = parseInput(args); + const project = resolveProjectOrThrow(args.dir); + const service: ShareService = createShareService(project.dir, (value) => { + if (value && !args.json) + process.stderr.write( + `Sharing: ${value.step}${value.slow ? " (still processing)" : ""}\r`, + ); + }); + await chooseAudience(input, args, service); + const result = await service.run(input); + await presentResult(result, input, Boolean(args.json)); + } catch (error) { + const failure = shareError(error); + if (args.json) console.log(JSON.stringify(jsonFailure(failure.code, failure.message))); + else console.error(failure.message); + setCommandExitCode(error instanceof CliUsageError ? 2 : 1); + } + }, +}); + +interface ShareArgs { + public?: boolean; + team?: boolean; + "invite-only"?: boolean; + private?: boolean; + update?: boolean; + status?: boolean; + manage?: boolean; + yes?: boolean; + json?: boolean; + "wait-seconds"?: string; + space?: string; +} +function parseInput(args: ShareArgs): ShareAction { + const waitSeconds = Number(args["wait-seconds"]); + if (!Number.isInteger(waitSeconds) || waitSeconds < 1 || waitSeconds > 1800) + throw new CliUsageError("--wait-seconds must be an integer from 1 to 1800."); + if ([args.update, args.status, args.manage].filter(Boolean).length > 1) + throw new CliUsageError("Choose only one of --update, --status or --manage."); + const audience = requestedAudience(args); + const action = args.status ? "status" : args.manage ? "manage" : args.update ? "update" : "share"; + + return { action, audience, space: args.space, waitSeconds }; +} + +function requestedAudience(args: ShareArgs) { + const audiences: NonNullable[] = []; + if (args.public) audiences.push("public"); + if (args.team) audiences.push("team"); + if (args["invite-only"]) audiences.push("invite"); + if (args.private) audiences.push("private"); + if (audiences.length > 1) throw new CliUsageError("Choose one first-share audience."); + return audiences[0]; +} + +function shouldPrompt(input: ShareAction, args: ShareArgs) { + return input.action === "share" && !input.audience && !args.yes && !args.json && !isUnattended(); +} + +async function chooseAudience(input: ShareAction, args: ShareArgs, service: ShareService) { + if (!shouldPrompt(input, args)) return; + if ((await service.status()).share) return; + const selected = await prompts.select({ + message: "Who should be able to open this review?", + options: [ + { value: "public", label: "Anyone with the link (available on Free)" }, + { value: "team", label: "Workspace members" }, + { value: "invite", label: "Invited people" }, + { value: "private", label: "Only me" }, + ], + }); + if (prompts.isCancel(selected)) throw new CliUsageError("Sharing cancelled."); + if ( + selected === "public" || + selected === "team" || + selected === "invite" || + selected === "private" + ) + input.audience = selected; +} + +async function presentResult(result: ShareState, input: ShareAction, json: boolean) { + if (json) console.log(JSON.stringify({ ok: true, ...result })); + else if (input.action === "manage") { + console.log(result.manageUrl); + if (!isUnattended()) await (await import("open")).default(result.manageUrl); + } else if (result.ready) console.log(`Shared video ready: ${result.url}`); + else if (result.state === "not_shared") console.log("This project has not been shared yet."); + else if (result.state === "link_off") + console.log("This share's link is off. Run hyperframes share --manage to turn it on."); + else console.log("Your video is still processing. Run hyperframes share --status to check it."); +} diff --git a/packages/cli/src/share/auth.test.ts b/packages/cli/src/share/auth.test.ts new file mode 100644 index 0000000000..ded5049539 --- /dev/null +++ b/packages/cli/src/share/auth.test.ts @@ -0,0 +1,63 @@ +import { beforeEach, describe, expect, it, vi } from "vitest"; +import type { ResolvedCredential } from "../auth/resolver.js"; +const mocks = vi.hoisted(() => ({ + resolve: vi.fn<() => Promise>(), + refresh: vi.fn(), + user: vi.fn(), +})); +vi.mock("../auth/resolver.js", () => ({ resolveCredential: mocks.resolve })); +vi.mock("../auth/oauth.js", () => ({ refreshTokens: mocks.refresh })); +vi.mock("../auth/client.js", () => ({ + apiBaseUrl: () => "https://api.heygen.com", + AuthClient: class { + getCurrentUser = mocks.user; + }, +})); +import { createShareAccess } from "./auth.js"; +const oauth = (token: string): ResolvedCredential => ({ + type: "oauth", + access_token: token, + source: "file_json", + refreshable: false, +}); +beforeEach(() => { + vi.resetAllMocks(); + mocks.user.mockResolvedValue({ username: "owner", email: "owner@example.com" }); +}); +describe("share OAuth identity", () => { + it("rejects API keys before any account request", async () => { + mocks.resolve.mockResolvedValue({ type: "api_key", key: "secret", source: "env" }); + await expect(createShareAccess().access()).rejects.toMatchObject({ code: "UNAUTHENTICATED" }); + expect(mocks.user).not.toHaveBeenCalled(); + }); + it("never falls back to an API key after refresh", async () => { + mocks.resolve + .mockResolvedValueOnce({ + ...oauth("old"), + type: "oauth", + access_token: "old", + refresh_token: "refresh", + refreshable: true, + }) + .mockResolvedValueOnce({ type: "api_key", key: "key", source: "env" }); + await expect(createShareAccess().access()).rejects.toMatchObject({ code: "UNAUTHENTICATED" }); + expect(mocks.refresh).toHaveBeenCalledWith("refresh"); + expect(mocks.user).not.toHaveBeenCalled(); + }); + it("resolves the actor again when the credential changes", async () => { + mocks.resolve.mockResolvedValueOnce(oauth("a")).mockResolvedValueOnce(oauth("b")); + mocks.user + .mockResolvedValueOnce({ username: "first" }) + .mockResolvedValueOnce({ username: "second" }); + const auth = createShareAccess(); + expect((await auth.access()).owner).toBe("first"); + expect((await auth.access()).owner).toBe("second"); + }); + it("does not retry a refused environment token", async () => { + mocks.resolve.mockResolvedValue(oauth("refused")); + await expect(createShareAccess().access("refused")).rejects.toMatchObject({ + code: "UNAUTHENTICATED", + }); + expect(mocks.refresh).not.toHaveBeenCalled(); + }); +}); diff --git a/packages/cli/src/share/auth.ts b/packages/cli/src/share/auth.ts new file mode 100644 index 0000000000..1dc82c5129 --- /dev/null +++ b/packages/cli/src/share/auth.ts @@ -0,0 +1,60 @@ +import { apiBaseUrl, AuthClient } from "../auth/client.js"; +import { tokenEndpoint, oauthEnvironment } from "../auth/config.js"; +import { AuthError } from "../auth/errors.js"; +import { refreshTokens } from "../auth/oauth.js"; +import { resolveCredential } from "../auth/resolver.js"; + +export function shareSite(): string { + return oauthEnvironment() === "dev" ? "https://dev.hyperframes.dev" : "https://hyperframes.dev"; +} + +export function createShareAccess() { + let identity: { token: string; owner: string; email: string | null } | undefined; + const userClient = new AuthClient(); + const access = async (refused?: string) => { + const credential = await shareCredential(refused); + if (identity?.token !== credential.access_token) { + const user = await userClient.getCurrentUser(credential); + if (!user.username) throw loginRequired(); + identity = { + token: credential.access_token, + owner: user.username, + email: user.email ?? null, + }; + } + return { + token: credential.access_token, + heygen: new URL(tokenEndpoint()).origin, + heygenApi: apiBaseUrl(), + owner: identity.owner, + }; + }; + return { + access, + signedInEmail: async () => { + await access(); + return identity?.email ?? null; + }, + }; +} + +function loginRequired(): AuthError { + return new AuthError( + "UNAUTHENTICATED", + "Sharing requires a signed-in HeyGen account.", + "Run hyperframes auth login. API keys cannot own shared projects.", + ); +} + +async function shareCredential(refused?: string) { + let credential = await resolveCredential(); + if (credential.type !== "oauth") throw loginRequired(); + if (credential.refreshable || credential.access_token === refused) { + if (!credential.refresh_token) throw loginRequired(); + await refreshTokens(credential.refresh_token); + credential = await resolveCredential(); + if (credential.type !== "oauth") throw loginRequired(); + } + if (credential.access_token === refused) throw loginRequired(); + return credential; +} diff --git a/packages/cli/src/share/errors.ts b/packages/cli/src/share/errors.ts new file mode 100644 index 0000000000..05ce171243 --- /dev/null +++ b/packages/cli/src/share/errors.ts @@ -0,0 +1,37 @@ +import { ReviewFailed, reviewSentence } from "@hyperframes/share"; +import { isAuthError } from "../auth/errors.js"; +import { CliUsageError } from "../utils/commandResult.js"; + +const HINTS: Record = { + review_upload_origins_required: + "Review video storage is not configured. Set HYPERFRAMES_REVIEW_UPLOAD_ORIGINS to the exact storage origins provided by your deployment.", + review_project_limit_reached: + "Your workspace has used its five free shared projects. Update an existing share, or manage and remove one to free a slot. Turning a link off does not free a slot.", + review_subscription_required: + "That sharing option is not included in this workspace's plan. Choose an available audience explicitly or manage your plan.", + workspace_mismatch: + "This folder already shares into another workspace. Manage the existing share instead of changing its identity.", + review_binding_changed: + "The review linked to this folder changed. Run hyperframes share --status before trying again.", + manage_existing_audience: + "Manage this existing share to change its audience. Copying or updating a share preserves its settings.", + not_shared: + "This project has no shared review yet. Run hyperframes share with an explicit audience.", +}; +export function shareError(error: unknown): { code: string; message: string } { + if (error instanceof CliUsageError) return { code: error.code, message: error.message }; + if (isAuthError(error)) + return { + code: error.code.toLowerCase(), + message: `${error.message} ${error.hint ?? ""}`.trim(), + }; + if (error instanceof ReviewFailed) + return { + code: error.reason || "share_failed", + message: HINTS[error.reason] ?? reviewSentence(error), + }; + return { + code: "share_failed", + message: error instanceof Error ? error.message : "Sharing failed. Try again.", + }; +} diff --git a/packages/cli/src/share/host.ts b/packages/cli/src/share/host.ts new file mode 100644 index 0000000000..9ca09afafb --- /dev/null +++ b/packages/cli/src/share/host.ts @@ -0,0 +1,67 @@ +import { basename } from "node:path"; +import { realpathSync } from "node:fs"; +import { + bindShareHost, + projectFingerprint, + ReviewFailed, + setReviewSite, + signedInRequest, +} from "@hyperframes/share"; +import { reviewUploadOrigins } from "@hyperframes/share/host.mjs"; +import { findFFprobe } from "../browser/ffmpeg.js"; +import { latestShareRender } from "./render.js"; +import { shareSite } from "./auth.js"; +import { cliReviewUploadOrigins } from "./uploadOrigins.js"; + +const projects = new Set(); + +function isStorageOrigin(origin: string): boolean { + if (!URL.canParse(origin)) return false; + const url = new URL(origin); + const loopback = url.protocol === "http:" && url.hostname === "127.0.0.1"; + return ( + url.origin === origin && !url.hostname.includes("*") && (url.protocol === "https:" || loopback) + ); +} + +export function assertReviewUploadStorage(): void { + const origins = reviewUploadOrigins().filter(Boolean); + if (origins.length === 0 || !origins.every(isStorageOrigin)) + throw new ReviewFailed(503, "review_upload_origins_required"); +} + +export function bindCliShareProject(path: string): string { + const dir = realpathSync(path); + projects.add(dir); + bindShareHost({ + reviewUploadOrigins: cliReviewUploadOrigins(), + normalize: realpathSync, + assertOpenProject: (path) => { + const normalized = realpathSync(path); + if (!projects.has(normalized)) throw new Error("This project is not open for sharing."); + return normalized; + }, + resolveOpenProjectByPath: (path) => { + const normalized = realpathSync(path); + return projects.has(normalized) ? { id: normalized, dir: normalized } : null; + }, + listOpenProjects: () => [...projects].map((dir) => ({ dir })), + homeName: basename, + latestExportFile: latestShareRender, + projectFingerprint, + signedInRequest: (deps) => + signedInRequest({ + ...deps, + headers: { "X-HeyGen-Source": "cli", "X-HeyGen-Client-Source": "hyperframes" }, + }), + ffBinary: () => { + const binary = findFFprobe(); + if (!binary) throw new Error("Install FFmpeg to prepare a shared video."); + return binary; + }, + channelSite: "https://hyperframes.dev", + signinSites: ["https://hyperframes.dev", "https://dev.hyperframes.dev"], + }); + setReviewSite(shareSite()); + return dir; +} diff --git a/packages/cli/src/share/render.lifecycle.test.ts b/packages/cli/src/share/render.lifecycle.test.ts new file mode 100644 index 0000000000..b57884d185 --- /dev/null +++ b/packages/cli/src/share/render.lifecycle.test.ts @@ -0,0 +1,61 @@ +import { afterEach, beforeEach, expect, it, vi } from "vitest"; +import { existsSync, mkdtempSync, realpathSync, readdirSync, rmSync, writeFileSync } from "node:fs"; +import { tmpdir } from "node:os"; +import { join } from "node:path"; +import type { RenderExecutionDependencies } from "../commands/render/execute.js"; +import type { RenderOptions } from "../commands/render.js"; +const mocks = vi.hoisted(() => ({ render: vi.fn(), plan: vi.fn(), execute: vi.fn() })); +vi.mock("@hyperframes/share", () => ({ projectFingerprint: async () => "unchanged" })); +vi.mock("../commands/render/plan.js", () => ({ createRenderPlan: mocks.plan })); +vi.mock("../commands/render/execute.js", () => ({ executeRenderPlan: mocks.execute })); +vi.mock("../commands/render.js", () => ({ + renderLocal: mocks.render, + checkRenderResolutionPreflight: vi.fn(), +})); +import { latestShareRender, prepareShareRender } from "./render.js"; +let project: string; +const options: RenderOptions = { + fps: { num: 30, den: 1 }, + quality: "standard", + format: "mp4", + gpu: false, + browserGpuMode: "software", + hdrMode: "auto", + quiet: true, + exitAfterComplete: true, +}; +beforeEach(() => { + vi.resetAllMocks(); + project = realpathSync(mkdtempSync(join(tmpdir(), "hf-share-render-lifecycle-"))); + mocks.plan.mockImplementation((plan) => plan); + mocks.execute.mockImplementation( + async (plan: { output: string }, dependencies: RenderExecutionDependencies) => { + await dependencies.renderLocal(project, plan.output, options); + }, + ); + mocks.render.mockImplementation(async (_dir: string, output: string) => { + writeFileSync(output, "rendered-video"); + }); +}); +afterEach(() => rmSync(project, { recursive: true, force: true })); +it("keeps rendering embedded even when the command plan asks to exit", async () => { + await prepareShareRender(project); + expect(mocks.render).toHaveBeenCalledWith( + project, + expect.any(String), + expect.objectContaining({ embedded: true, exitAfterComplete: false }), + undefined, + ); + expect(options.exitAfterComplete).toBe(true); + expect(latestShareRender(project)?.fingerprint).toBe("unchanged"); +}); +it("propagates render failures without publishing a successful artifact record", async () => { + const error = new Error("render failed"); + mocks.render.mockImplementation(async (_dir: string, output: string) => { + writeFileSync(output, "partial-video"); + throw error; + }); + await expect(prepareShareRender(project)).rejects.toBe(error); + expect(existsSync(join(project, ".hyperframes", "share-render.json"))).toBe(false); + expect(readdirSync(join(project, ".hyperframes", "share-renders"))).toEqual([]); +}); diff --git a/packages/cli/src/share/render.test.ts b/packages/cli/src/share/render.test.ts new file mode 100644 index 0000000000..0d45d9c390 --- /dev/null +++ b/packages/cli/src/share/render.test.ts @@ -0,0 +1,44 @@ +import { mkdtempSync, mkdirSync, realpathSync, rmSync, symlinkSync, writeFileSync } from "node:fs"; +import { tmpdir } from "node:os"; +import { join } from "node:path"; +import { afterEach, describe, expect, it } from "vitest"; +import { latestShareRender, prepareShareRender } from "./render.js"; +const dirs: string[] = []; +function folder() { + const dir = realpathSync(mkdtempSync(join(tmpdir(), "hf-share-"))); + dirs.push(dir); + return dir; +} +afterEach(() => { + for (const dir of dirs.splice(0)) rmSync(dir, { recursive: true, force: true }); +}); +describe("local sharing render boundary", () => { + it("rejects a symlinked state directory before creating descendants", async () => { + const dir = folder(); + const outside = folder(); + writeFileSync(join(dir, "index.html"), ""); + symlinkSync(outside, join(dir, ".hyperframes")); + await expect(prepareShareRender(dir)).rejects.toThrow("without symlinks"); + }); + it("does not accept a sidecar pointing outside the project", () => { + const dir = folder(); + mkdirSync(join(dir, ".hyperframes")); + writeFileSync( + join(dir, ".hyperframes", "share-render.json"), + JSON.stringify({ id: "../../escape", path: "/tmp/escape.mp4", fingerprint: "f" }), + ); + expect(latestShareRender(dir)).toBeNull(); + }); + it("reuses only the exact locally recorded file", () => { + const dir = folder(); + const id = "41c4587b-abcd-42ab-87ab-21a7b64cc010"; + const output = join(dir, ".hyperframes", "share-renders", `${id}.mp4`); + mkdirSync(join(dir, ".hyperframes", "share-renders"), { recursive: true }); + writeFileSync(output, "video"); + writeFileSync( + join(dir, ".hyperframes", "share-render.json"), + JSON.stringify({ id, path: output, fingerprint: "f" }), + ); + expect(latestShareRender(dir)).toEqual({ id, path: output, fingerprint: "f" }); + }); +}); diff --git a/packages/cli/src/share/render.ts b/packages/cli/src/share/render.ts new file mode 100644 index 0000000000..5cb4afb684 --- /dev/null +++ b/packages/cli/src/share/render.ts @@ -0,0 +1,92 @@ +import { randomUUID } from "node:crypto"; +import { existsSync, readFileSync, realpathSync } from "node:fs"; +import { mkdir, writeFile, rename, rm } from "node:fs/promises"; +import { join } from "node:path"; +import { projectFingerprint } from "@hyperframes/share"; + +export interface ShareRender { + path: string; + id: string; + fingerprint: string; +} + +export function latestShareRender(dir: string): ShareRender | null { + try { + const value: unknown = JSON.parse( + readFileSync(join(dir, ".hyperframes", "share-render.json"), "utf8"), + ); + if ( + !value || + typeof value !== "object" || + !("path" in value) || + !("id" in value) || + !("fingerprint" in value) + ) + return null; + if ( + typeof value.path !== "string" || + typeof value.id !== "string" || + typeof value.fingerprint !== "string" || + !/^[a-f0-9-]{36}$/.test(value.id) + ) + return null; + const expected = join(realpathSync(dir), ".hyperframes", "share-renders", `${value.id}.mp4`); + if (value.path !== expected || !existsSync(expected) || realpathSync(expected) !== expected) + return null; + return { path: expected, id: value.id, fingerprint: value.fingerprint }; + } catch { + return null; + } +} + +export async function prepareShareRender(dir: string): Promise { + const before = await projectFingerprint(dir); + const previous = latestShareRender(dir); + if (previous?.fingerprint === before) return; + const stateFolder = join(dir, ".hyperframes"); + if (existsSync(stateFolder) && realpathSync(stateFolder) !== stateFolder) + throw new Error("Sharing state must stay inside this project, without symlinks."); + await mkdir(stateFolder, { recursive: true }); + const folder = join(stateFolder, "share-renders"); + if (existsSync(folder) && realpathSync(folder) !== folder) + throw new Error("Sharing state must stay inside this project, without symlinks."); + await mkdir(folder, { recursive: true }); + if (realpathSync(folder) !== folder) + throw new Error("Sharing state must stay inside this project, without symlinks."); + const id = randomUUID(); + const output = join(folder, `${id}.mp4`); + const [{ createRenderPlan }, { executeRenderPlan }, render] = await Promise.all([ + import("../commands/render/plan.js"), + import("../commands/render/execute.js"), + import("../commands/render.js"), + ]); + const target = join(stateFolder, "share-render.json"); + const temporary = `${target}.${id}.tmp`; + try { + const plan = createRenderPlan({ dir, output, format: "mp4", quiet: true, strict: true }); + await executeRenderPlan(plan, { + renderLocal: (project, output, options, cancellation) => + render.renderLocal( + project, + output, + { ...options, embedded: true, exitAfterComplete: false }, + cancellation, + ), + renderDocker: async () => { + throw new Error("Share renders locally."); + }, + checkResolution: render.checkRenderResolutionPreflight, + }); + if (!existsSync(output)) + throw new Error("The render did not produce a video. Run hyperframes render to diagnose it."); + if ((await projectFingerprint(dir)) !== before) + throw new Error( + "The project changed while rendering. Share again to capture the current project.", + ); + await writeFile(temporary, JSON.stringify({ id, path: output, fingerprint: before })); + await rename(temporary, target); + } catch (error) { + await Promise.allSettled([rm(output, { force: true }), rm(temporary, { force: true })]); + throw error; + } +} diff --git a/packages/cli/src/share/service.test.ts b/packages/cli/src/share/service.test.ts new file mode 100644 index 0000000000..231525e256 --- /dev/null +++ b/packages/cli/src/share/service.test.ts @@ -0,0 +1,259 @@ +import { beforeEach, describe, expect, it, vi } from "vitest"; +const mocks = vi.hoisted(() => ({ + status: vi.fn(), + version: vi.fn(), + record: vi.fn(), + project: vi.fn(), + spaces: vi.fn(), + flags: vi.fn(), + render: vi.fn(), + create: vi.fn(), + add: vi.fn(), + pending: vi.fn(), + refresh: vi.fn(), +})); +vi.mock("@hyperframes/share", () => ({ + reviewClient: () => ({ project: mocks.project, spaces: mocks.spaces, reviewFlags: mocks.flags }), + reviewStatus: mocks.status, + reviewVersion: mocks.version, + reviewRecord: mocks.record, + shareForReview: mocks.create, + addVersion: mocks.add, + pendingReviewExport: mocks.pending, + refreshReviewExport: mocks.refresh, + setReviewAccess: vi.fn(), + turnOffReviewLink: vi.fn(), + ReviewFailed: class extends Error { + constructor( + public status: number, + public reason: string, + ) { + super(reason); + } + }, +})); +vi.mock("./auth.js", () => ({ + createShareAccess: () => ({ access: vi.fn() }), + shareSite: () => "https://hyperframes.dev", +})); +vi.mock("./host.js", () => ({ + assertReviewUploadStorage: vi.fn(), + bindCliShareProject: (path: string) => path, +})); +vi.mock("./render.js", () => ({ prepareShareRender: mocks.render })); +import { createShareService } from "./service.js"; +const shared = { + projectId: "project", + url: "https://hyperframes.dev/review/link", + access: "public", + space: { id: "space" }, +}; +beforeEach(() => { + vi.resetAllMocks(); + mocks.status.mockResolvedValue(null); + mocks.record.mockResolvedValue(null); + mocks.pending.mockResolvedValue(null); + mocks.version.mockResolvedValue({ last: null, source: "ready" }); + mocks.project.mockResolvedValue({ latest_ready_version_id: "version-id" }); + mocks.flags.mockResolvedValue({ versionSharing: true }); + mocks.spaces.mockResolvedValue([ + { + space_id: "space", + bound: true, + can_create_review: true, + review_entitlements: { + can_register_project: true, + allowed_collaborative_access_modes: ["public"], + }, + }, + ]); +}); +describe("share operation consent and identity", () => { + it("reads an existing link without rendering or creating a version", async () => { + mocks.status.mockResolvedValue(shared); + expect((await createShareService("/project").run({ action: "share" })).url).toBe(shared.url); + expect(mocks.render).not.toHaveBeenCalled(); + expect(mocks.create).not.toHaveBeenCalled(); + expect(mocks.add).not.toHaveBeenCalled(); + }); + it("never chooses an audience for unattended first share", async () => { + await expect(createShareService("/project").run({ action: "share" })).rejects.toMatchObject({ + code: "audience_required", + }); + expect(mocks.render).not.toHaveBeenCalled(); + expect(mocks.create).not.toHaveBeenCalled(); + }); + it("checks free quota before rendering", async () => { + mocks.spaces.mockResolvedValue([ + { + space_id: "space", + bound: true, + can_create_review: true, + review_entitlements: { can_register_project: false }, + }, + ]); + await expect( + createShareService("/project").run({ action: "share", audience: "public" }), + ).rejects.toMatchObject({ reason: "review_project_limit_reached" }); + expect(mocks.render).not.toHaveBeenCalled(); + }); + it("preserves existing workspace and audience", async () => { + mocks.status.mockResolvedValue(shared); + const service = createShareService("/project"); + await expect(service.run({ action: "update", space: "other" })).rejects.toMatchObject({ + reason: "workspace_mismatch", + }); + await expect(service.run({ action: "share", audience: "private" })).rejects.toMatchObject({ + reason: "manage_existing_audience", + }); + expect(mocks.render).not.toHaveBeenCalled(); + }); + it("refuses a public share opened while a private first share was rendering", async () => { + mocks.render.mockImplementation(async () => { + mocks.create.mockResolvedValue(shared); + }); + + await expect( + createShareService("/project").run({ action: "share", audience: "private" }), + ).rejects.toMatchObject({ reason: "manage_existing_audience" }); + expect(mocks.add).not.toHaveBeenCalled(); + }); + it("refuses a first share bound to another workspace during rendering", async () => { + mocks.render.mockImplementation(async () => { + mocks.create.mockResolvedValue({ ...shared, space: { id: "other" } }); + }); + + await expect( + createShareService("/project").run({ action: "share", audience: "public", space: "space" }), + ).rejects.toMatchObject({ reason: "workspace_mismatch" }); + expect(mocks.add).not.toHaveBeenCalled(); + }); + it("refuses an update when the folder changes review projects during rendering", async () => { + mocks.status.mockResolvedValue(shared); + mocks.render.mockImplementation(async () => { + mocks.status.mockResolvedValue({ ...shared, projectId: "different-project" }); + }); + + await expect(createShareService("/project").run({ action: "update" })).rejects.toMatchObject({ + reason: "review_binding_changed", + }); + expect(mocks.add).not.toHaveBeenCalled(); + }); + it("refuses an update when access changes during rendering", async () => { + mocks.status.mockResolvedValue({ ...shared, access: "private" }); + mocks.render.mockImplementation(async () => { + mocks.status.mockResolvedValue(shared); + }); + + await expect(createShareService("/project").run({ action: "update" })).rejects.toMatchObject({ + reason: "manage_existing_audience", + }); + expect(mocks.add).not.toHaveBeenCalled(); + }); + it("pins the approved project into a first upload", async () => { + mocks.create.mockImplementation(async () => { + mocks.status.mockResolvedValue(shared); + return shared; + }); + mocks.add.mockResolvedValue(null); + + await createShareService("/project").run({ action: "share", audience: "public" }); + + expect(mocks.create).toHaveBeenCalledWith(expect.objectContaining({ spaceId: "space" })); + expect(mocks.add).toHaveBeenCalledWith(expect.objectContaining({ projectId: "project" })); + }); + it("retries an unfinished first share in its saved workspace", async () => { + mocks.record.mockResolvedValue({ spaceId: "saved", projectId: "project" }); + mocks.spaces.mockResolvedValue([ + { space_id: "space", bound: true, can_create_review: true }, + { space_id: "saved", can_create_review: true }, + ]); + mocks.create.mockImplementation(async () => { + const saved = { ...shared, space: { id: "saved" }, access: "private" }; + mocks.status.mockResolvedValue(saved); + return saved; + }); + mocks.add.mockResolvedValue(null); + const service = createShareService("/project"); + + await expect( + service.run({ action: "share", audience: "private", space: "space" }), + ).rejects.toMatchObject({ reason: "workspace_mismatch" }); + expect(mocks.render).not.toHaveBeenCalled(); + await service.run({ action: "share", audience: "private" }); + expect(mocks.create).toHaveBeenCalledWith(expect.objectContaining({ spaceId: "saved" })); + expect(mocks.add).toHaveBeenCalledWith(expect.objectContaining({ projectId: "project" })); + }); + it("does not report a different project's link if the folder changes during upload", async () => { + mocks.status.mockResolvedValue(shared); + mocks.add.mockImplementation(async () => { + mocks.status.mockResolvedValue({ ...shared, projectId: "different-project" }); + return null; + }); + + await expect(createShareService("/project").run({ action: "update" })).rejects.toMatchObject({ + reason: "review_binding_changed", + }); + expect(mocks.add).toHaveBeenCalledWith(expect.objectContaining({ projectId: "project" })); + }); + it("does not label an old ready version as a completed update", async () => { + mocks.status.mockResolvedValue(shared); + mocks.add.mockResolvedValue(null); + mocks.version.mockResolvedValue({ last: { current: false }, source: "ready" }); + const result = await createShareService("/project").run({ action: "update" }); + expect(result).toMatchObject({ state: "processing", ready: false, url: null }); + }); + it("reports rejection discovered after the upload watch ends", async () => { + mocks.status.mockResolvedValue(shared); + mocks.add.mockResolvedValue(null); + mocks.refresh.mockResolvedValueOnce(undefined).mockImplementationOnce(async () => { + mocks.version.mockResolvedValue({ last: null, source: "ready", failure: "Video rejected." }); + }); + + await expect(createShareService("/project").run({ action: "update" })).rejects.toThrow( + "Video rejected.", + ); + }); + it("does not silently upload changed edits while resuming first share", async () => { + mocks.status.mockResolvedValue(shared); + mocks.project.mockResolvedValue({ latest_ready_version_id: null }); + mocks.version.mockResolvedValue({ last: null, source: "stale" }); + await expect(createShareService("/project").run({ action: "share" })).rejects.toThrow( + "--update", + ); + expect(mocks.render).not.toHaveBeenCalled(); + expect(mocks.add).not.toHaveBeenCalled(); + }); + it("keeps an off link off on repeat share", async () => { + mocks.status.mockResolvedValue({ ...shared, url: null }); + expect((await createShareService("/project").run({ action: "share" })).state).toBe("link_off"); + expect(mocks.create).not.toHaveBeenCalled(); + }); +}); + +describe("asynchronous share recovery", () => { + it("reconciles completion before reading project and local status", async () => { + mocks.status.mockResolvedValue(shared); + mocks.pending.mockResolvedValue({ projectId: "project", videoId: "video-id" }); + mocks.refresh.mockImplementation(async () => { + mocks.pending.mockResolvedValue(null); + }); + const result = await createShareService("/project").run({ action: "status" }); + expect(mocks.refresh).toHaveBeenCalledOnce(); + expect(mocks.refresh.mock.invocationCallOrder[0]).toBeLessThan( + mocks.project.mock.invocationCallOrder[0] ?? 0, + ); + expect(result).toMatchObject({ state: "ready", ready: true, url: shared.url }); + expect(mocks.add).not.toHaveBeenCalled(); + expect(mocks.render).not.toHaveBeenCalled(); + }); + it("keeps an active upload processing even if unrelated IDs happen to match", async () => { + mocks.status.mockResolvedValue(shared); + mocks.pending.mockResolvedValue({ projectId: "project", videoId: "version-id" }); + expect(await createShareService("/project").status()).toMatchObject({ + state: "processing", + ready: false, + url: null, + }); + }); +}); diff --git a/packages/cli/src/share/service.ts b/packages/cli/src/share/service.ts new file mode 100644 index 0000000000..adc9542d11 --- /dev/null +++ b/packages/cli/src/share/service.ts @@ -0,0 +1,224 @@ +import { basename } from "node:path"; +import { CliUsageError } from "../utils/commandResult.js"; +import { + addVersion, + pendingReviewExport, + refreshReviewExport, + reviewClient, + reviewRecord, + reviewStatus, + reviewVersion, + shareForReview, + setReviewAccess, + turnOffReviewLink, + ReviewFailed, + type AccessMode, + type ReviewClient, + type ReviewExportProgress, + type ReviewShare, +} from "@hyperframes/share"; +import { createShareAccess, shareSite } from "./auth.js"; +import { assertReviewUploadStorage, bindCliShareProject } from "./host.js"; +import { prepareShareRender } from "./render.js"; + +export interface ShareAction { + action: "share" | "update" | "status" | "manage"; + audience?: AccessMode; + space?: string; + waitSeconds?: number; +} +function linkState(share: ReviewShare | null, ready: boolean): string { + if (!share) return "not_shared"; + if (!share.url) return "link_off"; + return ready ? "ready" : "processing"; +} +async function readStatus(dir: string, client: ReviewClient, expectedProjectId?: string) { + const share = await reviewStatus({ projectPath: dir, client }); + if (expectedProjectId) assertUploadProject(share, expectedProjectId); + if (share) await refreshReviewExport(dir, client); + const project = await readProject(share, client); + const latest = project?.latest_ready_version_id ?? null; + const version = await reviewVersion(dir, { latestReadyVersionId: latest }); + const pending = await pendingReviewExport(dir); + const activeUrl = share?.url ?? null; + const processing = isProcessing(pending, share); + const ready = Boolean(activeUrl && latest && !processing); + return { + share, + version, + pending, + state: linkState(share, ready), + ready, + ...statusLinks(activeUrl, ready, processing, project), + }; +} +async function readProject(share: ReviewShare | null, client: ReviewClient) { + return share?.projectId ? client.project(share.projectId) : null; +} +function statusLinks( + url: string | null, + ready: boolean, + processing: boolean, + project: Awaited>, +) { + return { + url: ready ? url : null, + previousUrl: processing && project?.latest_ready_version_id ? url : null, + manageUrl: project?.authenticated_review_url ?? `${shareSite()}/shares`, + }; +} +function isProcessing( + pending: Awaited>, + share: ReviewShare | null, +) { + return Boolean(pending && pending.projectId === share?.projectId); +} +function selectSpace(spaces: Awaited>, id?: string) { + if (id) return spaces.find((space) => space.space_id === id); + return spaces.find((space) => space.bound) ?? spaces.find((space) => space.kind === "personal"); +} +function assertUploadProject(share: ReviewShare | null, expectedId?: string): string { + const id = share?.projectId; + if (!id || (expectedId && id !== expectedId)) + throw new ReviewFailed(409, "review_binding_changed"); + return id; +} +function assertExistingIntent(share: ReviewShare | null, input: ShareAction) { + if (!share) { + if (input.action === "update") throw new ReviewFailed(404, "not_shared"); + return; + } + if (input.space && share.space?.id !== input.space) + throw new ReviewFailed(409, "workspace_mismatch"); + if (input.audience && share.access !== input.audience) + throw new ReviewFailed(409, "manage_existing_audience"); +} +function retrievesExisting(current: ShareState, input: ShareAction) { + return current.share && input.action === "share" && current.state !== "processing"; +} +async function preflightFirst(dir: string, client: ReviewClient, input: ShareAction) { + const audience = input.audience; + if (!audience) + throw new CliUsageError( + "Choose an audience with --public, --team, --invite-only or --private. --yes is not audience consent.", + { code: "audience_required" }, + ); + const [spaces, record] = await Promise.all([client.spaces(), reviewRecord(dir)]); + const space = selectSpace(spaces, registrationSpace(record, input.space)); + if (!space || !space.can_create_review) throw new ReviewFailed(403, "workspace_cannot_share"); + assertQuota(record, space); + assertAudience(audience, space); + return space.space_id; +} +type Space = Awaited>[number]; +type ShareRecord = Awaited>; +function registrationSpace(record: ShareRecord, requested?: string) { + if (!record?.spaceId) return requested; + if (!requested || requested === record.spaceId) return record.spaceId; + if (record.registration || record.projectId) throw new ReviewFailed(409, "workspace_mismatch"); + return requested; +} +function assertQuota(record: ShareRecord, space: Space) { + if (record?.registration || record?.projectId) return; + if (space.review_entitlements?.can_register_project === false) + throw new ReviewFailed(402, "review_project_limit_reached"); +} +function assertAudience(audience: AccessMode, space: Space) { + if (audience === "private") return; + if (!space.review_entitlements?.allowed_collaborative_access_modes.includes(audience)) + throw new ReviewFailed(402, "review_subscription_required"); +} +function assertResumeSource(current: ShareState, input: ShareAction) { + if (current.share && input.action === "share" && current.version.source !== "ready") + throw new Error( + "The shared video is unfinished and local edits have changed. Run hyperframes share --update to explicitly upload the current project.", + ); +} +export function createShareService( + projectPath: string, + progress: (value: ReviewExportProgress | null) => void = () => {}, +) { + const dir = bindCliShareProject(projectPath); + const auth = createShareAccess(); + const client = reviewClient(auth); + const status = async (expectedProjectId?: string) => { + await auth.access(); + return readStatus(dir, client, expectedProjectId); + }; + const upload = async (input: ShareAction, projectId: string) => { + const end = Date.now() + (input.waitSeconds ?? 300) * 1000; + let added = false; + const failure = await addVersion({ + projectPath: dir, + projectId, + title: basename(dir), + client, + onProgress: progress, + allowPending: true, + onAdded: () => { + added = true; + }, + open: () => Date.now() < end, + }); + if (failure) throw new Error(failure); + const result = await status(projectId); + if (result.version.failure) throw new Error(result.version.failure); + if (!added && !result.version.last?.current) + return { ...result, state: "processing", ready: false, url: null }; + return result; + }; + const uploadTarget = async (current: ReviewShare | null, input: ShareAction, space?: string) => { + const share = current + ? await reviewStatus({ projectPath: dir, client }) + : await shareForReview({ + projectPath: dir, + title: basename(dir), + client, + spaceId: space, + audience: input.audience, + }); + const projectId = assertUploadProject(share, current?.projectId); + if (share?.takedown) throw new ReviewFailed(409, "moderation_hold"); + assertExistingIntent(share, { + ...input, + space: input.space ?? space, + audience: input.audience ?? current?.access, + }); + return projectId; + }; + const run = async (input: ShareAction) => { + const current = await status(); + if (input.action === "status" || input.action === "manage") return current; + assertExistingIntent(current.share, input); + if (retrievesExisting(current, input)) return current; + if (!(await client.reviewFlags()).versionSharing) + throw new ReviewFailed(403, "feature_unavailable"); + const space = current.share + ? current.share.space?.id + : await preflightFirst(dir, client, input); + assertResumeSource(current, input); + assertReviewUploadStorage(); + await prepareShareRender(dir); + return upload(input, await uploadTarget(current.share, input, space)); + }; + return { + status, + run, + capabilities: () => client.reviewFlags(), + spaces: () => client.spaces(), + setAccess: async (access: AccessMode) => { + await setReviewAccess({ projectPath: dir, client, change: { access } }); + return status(); + }, + linkOff: async () => { + await turnOffReviewLink({ projectPath: dir, client }); + return status(); + }, + linkOn: async () => { + await shareForReview({ projectPath: dir, title: basename(dir), client }); + return status(); + }, + }; +} +export type ShareService = ReturnType; +export type ShareState = Awaited>; diff --git a/packages/cli/src/share/uploadOrigins.test.ts b/packages/cli/src/share/uploadOrigins.test.ts new file mode 100644 index 0000000000..facba479c9 --- /dev/null +++ b/packages/cli/src/share/uploadOrigins.test.ts @@ -0,0 +1,90 @@ +import { afterEach, beforeEach, expect, it, vi } from "vitest"; +import { mkdtempSync, rmSync } from "node:fs"; +import { tmpdir } from "node:os"; +import { join } from "node:path"; +import { cliReviewUploadOrigins } from "./uploadOrigins.js"; +import { assertReviewUploadStorage, bindCliShareProject } from "./host.js"; +import { trustedUploadUrl } from "@hyperframes/share/reviewUpload.mjs"; + +let dir: string; +beforeEach(() => { + for (const key of [ + "HYPERFRAMES_REVIEW_UPLOAD_ORIGINS", + "HYPERFRAMES_ENV", + "HEYGEN_API_URL", + "HYPERFRAMES_OAUTH_TOKEN_URL", + "HYPERFRAMES_OAUTH_CLIENT_ID", + ]) + vi.stubEnv(key, undefined); + dir = mkdtempSync(join(tmpdir(), "share-upload-origins-")); +}); +afterEach(() => { + vi.unstubAllEnvs(); + rmSync(dir, { recursive: true, force: true }); +}); + +it("trusts only the production video and source storage origins by default", () => { + expect(cliReviewUploadOrigins()).toEqual([ + "https://heygen-hyperframes-reviews-prod-767398024897-us-east-2.s3.amazonaws.com", + "https://heygen-hyperframes-reviews-prod-767398024897-us-east-2.s3.us-east-2.amazonaws.com", + "https://hyperframes-composition-sync-prod.s3.us-east-2.amazonaws.com", + ]); + bindCliShareProject(dir); + expect(() => assertReviewUploadStorage()).not.toThrow(); + for (const origin of cliReviewUploadOrigins()) + expect(trustedUploadUrl(`${origin}/object?signature=fixture`)).not.toBeNull(); +}); +it.each([ + ["HYPERFRAMES_ENV", "dev"], + ["HEYGEN_API_URL", "https://custom.example"], + ["HYPERFRAMES_OAUTH_TOKEN_URL", "https://custom.example/token"], + ["HYPERFRAMES_OAUTH_CLIENT_ID", "custom-client"], +])("does not inherit production trust when %s changes", (key, value) => { + bindCliShareProject(dir); + const production = cliReviewUploadOrigins()[0]; + vi.stubEnv(key, value); + bindCliShareProject(dir); + expect(cliReviewUploadOrigins()).toEqual([]); + expect(() => assertReviewUploadStorage()).toThrow(); + expect(trustedUploadUrl(`${production}/object`)).toBeNull(); +}); +it("replaces defaults with an explicit exact-origin override for custom deployments", () => { + vi.stubEnv("HYPERFRAMES_ENV", "dev"); + vi.stubEnv( + "HYPERFRAMES_REVIEW_UPLOAD_ORIGINS", + " https://storage.example , https://sources.example ", + ); + bindCliShareProject(dir); + expect(cliReviewUploadOrigins()).toEqual(["https://storage.example", "https://sources.example"]); + expect(() => assertReviewUploadStorage()).not.toThrow(); + expect(trustedUploadUrl("https://storage.example/object")).not.toBeNull(); + expect( + trustedUploadUrl("https://hyperframes-composition-sync-prod.s3.us-east-2.amazonaws.com/object"), + ).toBeNull(); +}); +it.each(["", " , "])("keeps explicit empty overrides fail-closed (%j)", (override) => { + vi.stubEnv("HYPERFRAMES_REVIEW_UPLOAD_ORIGINS", override); + bindCliShareProject(dir); + expect(cliReviewUploadOrigins()).toEqual([]); + expect(() => assertReviewUploadStorage()).toThrow(); +}); +it("rejects sibling buckets, userinfo, non-HTTPS and accelerated hosts", () => { + bindCliShareProject(dir); + for (const url of [ + "https://other-bucket.s3.us-east-2.amazonaws.com/object", + "https://hyperframes-composition-sync-prod.s3.us-east-2.amazonaws.com.evil.example/object", + "https://user:password@hyperframes-composition-sync-prod.s3.us-east-2.amazonaws.com/object", + "http://hyperframes-composition-sync-prod.s3.us-east-2.amazonaws.com/object", + "https://heygen-hyperframes-reviews-prod-767398024897-us-east-2.s3-accelerate.amazonaws.com/object", + ]) + expect(trustedUploadUrl(url)).toBeNull(); +}); + +it.each(["https://storage.example/path", "https://*.example", "http://storage.example"])( + "does not accept invalid override %s", + (override) => { + vi.stubEnv("HYPERFRAMES_REVIEW_UPLOAD_ORIGINS", override); + bindCliShareProject(dir); + expect(() => assertReviewUploadStorage()).toThrow(); + }, +); diff --git a/packages/cli/src/share/uploadOrigins.ts b/packages/cli/src/share/uploadOrigins.ts new file mode 100644 index 0000000000..2b910ffd91 --- /dev/null +++ b/packages/cli/src/share/uploadOrigins.ts @@ -0,0 +1,28 @@ +import { apiBaseUrl } from "../auth/client.js"; +import { + defaultClientId, + oauthEnvironment, + resolveClientId, + tokenEndpoint, +} from "../auth/config.js"; + +const PRODUCTION_UPLOAD_ORIGINS = [ + "https://heygen-hyperframes-reviews-prod-767398024897-us-east-2.s3.amazonaws.com", + "https://heygen-hyperframes-reviews-prod-767398024897-us-east-2.s3.us-east-2.amazonaws.com", + "https://hyperframes-composition-sync-prod.s3.us-east-2.amazonaws.com", +] as const; + +export function cliReviewUploadOrigins(): readonly string[] { + const override = process.env.HYPERFRAMES_REVIEW_UPLOAD_ORIGINS; + if (override !== undefined) + return override + .split(",") + .map((origin) => origin.trim()) + .filter(Boolean); + const standardProduction = + oauthEnvironment() === "prod" && + apiBaseUrl() === "https://api.heygen.com" && + tokenEndpoint() === "https://api2.heygen.com/v1/oauth/token" && + resolveClientId() === defaultClientId(); + return standardProduction ? PRODUCTION_UPLOAD_ORIGINS : []; +} diff --git a/packages/cli/src/utils/render-success-state.test.ts b/packages/cli/src/utils/render-success-state.test.ts index 95c084c42a..db645ddea6 100644 --- a/packages/cli/src/utils/render-success-state.test.ts +++ b/packages/cli/src/utils/render-success-state.test.ts @@ -40,6 +40,7 @@ describe("runPostRenderStep", () => { const originalExitCode = process.exitCode; beforeEach(() => { + markRenderSucceeded(); registerRootExitCodeSanitizer(() => { process.exitCode = 0; }); @@ -126,6 +127,7 @@ describe("runPostRenderStepAsync", () => { const originalExitCode = process.exitCode; beforeEach(() => { + markRenderSucceeded(); registerRootExitCodeSanitizer(() => { process.exitCode = 0; }); @@ -164,3 +166,30 @@ describe("runPostRenderStepAsync", () => { expect(process.exitCode).toBe(0); }); }); + +it("does not sanitize the host exit code after embedded-render cleanup fails", async () => { + _resetRenderSuccessForTests(); + const sanitize = vi.fn(); + registerRootExitCodeSanitizer(sanitize); + try { + runPostRenderStep( + "metrics", + () => { + throw new Error("metrics failed"); + }, + vi.fn(), + ); + await runPostRenderStepAsync( + "history", + async () => { + throw new Error("history failed"); + }, + vi.fn(), + ); + expect(sanitize).not.toHaveBeenCalled(); + expect(isRenderSucceeded()).toBe(false); + } finally { + registerRootExitCodeSanitizer(() => {}); + _resetRenderSuccessForTests(); + } +}); diff --git a/packages/cli/src/utils/render-success-state.ts b/packages/cli/src/utils/render-success-state.ts index 531d6ba6a9..1e0bce5ec5 100644 --- a/packages/cli/src/utils/render-success-state.ts +++ b/packages/cli/src/utils/render-success-state.ts @@ -69,10 +69,10 @@ const defaultErrorSink: PostRenderErrorSink = (message) => { /** * Run a post-artifact-validated cleanup step so a throw cannot flip the CLI - * exit code. `markRenderSucceeded()` MUST have been called first — this - * helper is only safe on the success path where the artifact is already - * committed to disk. Logs a compact warning to stderr, asks the root CLI to - * clear a stray exit code, and swallows the error. + * exit code. Use only after the artifact is committed to disk. Logs a compact + * warning and swallows the error. Only a top-level render that called + * `markRenderSucceeded()` may ask the root CLI to clear a stray exit code; + * an embedded render does not own the surrounding command’s outcome. */ export function runPostRenderStep( label: string, @@ -103,5 +103,5 @@ function reportPostRenderStepFailure(label: string, err: unknown, sink: PostRend sink(` [hyperframes] Post-render step '${label}' failed (render already succeeded): ${message}`); // The failing step (or something it triggered) may have set a non-zero // exitCode. The render succeeded, so ask the root CLI owner to clear it. - sanitizeSuccessfulExitCode(); + if (isRenderSucceeded()) sanitizeSuccessfulExitCode(); } diff --git a/packages/cli/tsup.config.ts b/packages/cli/tsup.config.ts index 6992026bdb..2089f2e205 100644 --- a/packages/cli/tsup.config.ts +++ b/packages/cli/tsup.config.ts @@ -77,6 +77,7 @@ var __dirname = __hf_dirname(__filename);`, "@hyperframes/gcp-cloud-run/terraform", ], noExternal: [ + "@hyperframes/share", "@hyperframes/core", "@hyperframes/parsers", "@hyperframes/studio-server", diff --git a/packages/share/src/reviewExport.mjs b/packages/share/src/reviewExport.mjs index 042ca4d26f..f35f8166ff 100644 --- a/packages/share/src/reviewExport.mjs +++ b/packages/share/src/reviewExport.mjs @@ -49,10 +49,11 @@ import { versionSentence } from "./reviewVersionSentences.mjs"; /** `projectId` overrides the recorded review project; `open`: a held video is watched only while the project is open. * `filesForExport`: the synced snapshot a new version carries, null for - * none. + * none. `allowPending` lets a host treat accepted processing or screening as a successful return. * @typedef {VersionHooks & { projectPath: string, title: string, client: ReviewClient, put?: typeof putFile, * sleep?: (ms: number) => Promise, probe?: (file: string) => Promise, now?: () => number, - * projectId?: string | null, filesForExport?: FilesForRender, fromReview?: FromReview | null }} VersionRequest */ + * projectId?: string | null, filesForExport?: FilesForRender, fromReview?: FromReview | null, + * allowPending?: boolean }} VersionRequest */ /** The snapshot of `rendered`, the project as the export was rendered; null when the folder is not that render. * @typedef {(projectPath: string, rendered: string | null) => Promise} @@ -640,7 +641,7 @@ async function sendVersion(r, report, source, id, state) { /** @param {Required} r @param {VersionRecord} state * @param {NonNullable} pending @param {string} id @param {ExportDTO} done @param {boolean} first */ async function finishRun(r, state, pending, id, done, first) { - if (going(done)) return stillGoing(done); + if (going(done)) return r.allowPending ? null : stillGoing(done); const failed = await finish(r.projectPath, state, pending, id, done, r.fromReview); if (!failed) { const fromReview = pending.reviewSent?.value; @@ -663,6 +664,7 @@ export async function addVersion(request) { now: () => Date.now(), onProgress: () => {}, open: () => true, + allowPending: false, filesForExport: async () => null, fromReview: null, onAdded: () => {}, @@ -755,7 +757,7 @@ async function settleSavedExport(dir, client, fromReview) { const id = await reviewProjectId(dir); if (!pending?.videoId || !id || pending.projectId !== id) return; const done = await client.readExport(id, pending.videoId); - if (going(done)) return; + if (done.status === "upload_pending" || going(done)) return; const failure = await finish(dir, state, pending, id, done, fromReview); const key = normalize(dir); if (failure) failures.set(key, { ...failure, exportKey: exportKeyOf(dir) }); diff --git a/packages/share/tests/kernel.test.mjs b/packages/share/tests/kernel.test.mjs index 90a1747c2a..cbb38c1832 100644 --- a/packages/share/tests/kernel.test.mjs +++ b/packages/share/tests/kernel.test.mjs @@ -12,6 +12,7 @@ import { shareForReview, reviewRecord, addVersion, + pendingReviewExport, reviewVersion, refreshReviewExport, putFile, @@ -146,6 +147,45 @@ test("HTML stamps and generated render metadata do not dirty the shared source", await writeFile(join(dir, "index.html"), '
Changed
'); assert.notEqual(await projectFingerprint(dir), before); }); +test("a host can accept a version that is still screening when it stops waiting", async (t) => { + const dir = await folder(t); + const api = client(); + await shareForReview({ projectPath: dir, title: "Video", client: api, audience: "public" }); + await writeFile(join(dir, ".hyperframes/video.mp4"), "video bytes"); + bindShareHost({ projectFingerprint: async () => "rendered" }); + t.after(() => bindShareHost({ projectFingerprint })); + let video = { + status: "screening", + screening_state: "held", + video_id: "vid", + version_id: "v1", + exported_at: "2026-11-04T00:00:00Z", + }; + api.createExport = t.mock.fn(async () => video); + api.readExport = async () => video; + const onAdded = t.mock.fn(); + const request = { + projectPath: dir, + title: "Video", + client: api, + probe: async () => ({ width: 1920, height: 1080, duration: 1 }), + open: () => false, + onAdded, + }; + + assert.ok(await addVersion(request)); + assert.equal((await reviewVersion(dir)).held, true); + assert.equal(await addVersion({ ...request, allowPending: true }), null); + assert.equal((await pendingReviewExport(dir)).videoId, "vid"); + assert.equal((await reviewVersion(dir)).failure, null); + assert.equal(onAdded.mock.callCount(), 0); + assert.equal(api.createExport.mock.callCount(), 1); + + video = { ...video, status: "ready" }; + await refreshReviewExport(dir, api); + assert.equal(await pendingReviewExport(dir), null); + assert.equal((await reviewVersion(dir)).last.current, true); +}); const moduleUrl = new URL("../src/index.mjs", import.meta.url).href; function child(script, args) { return spawn(process.execPath, ["--input-type=module", "-e", script, ...args], { @@ -232,13 +272,15 @@ test("status recovery settles distinct video/version IDs without a new upload", }, }), ); + const saved = await readFile(file, "utf8"); + let status = "upload_pending"; let reads = 0; api.readExport = async (project, video) => { reads++; assert.equal(project, "p1"); assert.equal(video, "video-id"); return { - status: "ready", + status, video_id: video, version_id: "version-id", exported_at: "2026-11-04T00:00:00Z", @@ -248,13 +290,17 @@ test("status recovery settles distinct video/version IDs without a new upload", assert.equal(reads, 0); await refreshReviewExport(dir, api); assert.equal(reads, 1); + assert.equal(await readFile(file, "utf8"), saved); + status = "ready"; + await refreshReviewExport(dir, api); + assert.equal(reads, 2); assert.equal(JSON.parse(await readFile(file, "utf8")).pending, null); assert.equal( (await reviewVersion(dir, { latestReadyVersionId: "version-id" })).last.current, true, ); await refreshReviewExport(dir, api); - assert.equal(reads, 1); + assert.equal(reads, 2); }); test("refuses an unconfigured review upload destination before sending the file", async (t) => { const dir = await folder(t);