diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml index 06be500b87..ea00c92088 100644 --- a/.github/workflows/ci.yml +++ b/.github/workflows/ci.yml @@ -231,7 +231,11 @@ jobs: - "packages/lint/src/**" - "packages/cli/src/{cli,help,version}.ts" - "packages/cli/src/renderSetupWorker*.ts" - - "packages/cli/src/commands/{preview*,add,browser}.ts" + - "packages/cli/src/commands/{preview*,add,browser,batchRender,render}.ts" + - "packages/cli/src/commands/render/**" + - "packages/cli/src/share/**" + - "packages/cli/src/cloud/parsing.ts" + - "packages/share/{src,scripts}/**" - "packages/cli/src/server/**" - "packages/cli/src/browser/**" - "packages/cli/src/utils/**" @@ -239,7 +243,7 @@ jobs: - "packages/cli/src/{background-removal,registry,telemetry}/**" - "packages/cli/src/capture/{captureCompositionFrame,captureTimeout,navigateForCapture,readBoundedResponse}.ts" - "packages/cli/src/media-use/lib/config-lock.mjs" - - "packages/cli/src/auth/{config,errors,paths,telemetryIdentity}.ts" + - "packages/cli/src/auth/**" - "packages/cli/scripts/**" - "packages/core/stubs/**" - "packages/engine/src/**" @@ -248,7 +252,7 @@ jobs: - "packages/producer/scripts/build-hf-early-stub.ts" - "packages/producer/build*.mjs" - "packages/player/scripts/verify-runtime-pin.mjs" - - "packages/{studio,studio-server,core,parsers,player,sdk,lint,cli,engine,producer}/{package.json,tsconfig.json,tsup.config.ts}" + - "packages/{studio,studio-server,core,parsers,player,sdk,lint,cli,engine,producer,share}/{package.json,tsconfig.json,tsup.config.ts}" - "packages/*/package-subpaths.json" - "scripts/package-subpaths.mjs" - "scripts/rewrite-relative-import-extensions.mjs" diff --git a/docs/guides/export-and-share.mdx b/docs/guides/export-and-share.mdx index 29aaa74d0e..2f190c166d 100644 --- a/docs/guides/export-and-share.mdx +++ b/docs/guides/export-and-share.mdx @@ -161,3 +161,37 @@ editor or its render queue. - [Export and manage renders in the browser editor](/studio/export) - [Use advanced rendering options](/guides/rendering) - [Diagnose a project or render failure](/help) + +## Share from the local Studio preview + +Open a project with `hyperframes preview`, then choose **Share** beside **Export**. +Choose **Sign in** if prompted. You can also run +`hyperframes auth login` in your terminal, then return to Studio. Sharing reconnects +automatically after browser sign-in or when you return to the panel. Credentials stay +in the local CLI process. If you switch accounts in the terminal, reload Studio +or sign in from the panel before retrying. + +Choose the workspace and who can access the project, then choose **Create share +link**. Studio finishes saving pending edits before it renders and uploads the +project. The five free shared-project allowance is the same allowance used by +Desktop and the CLI. The workspace meter comes from the server; retries of an +existing registration do not need an extra slot. + +Project files are included when available for the workspace. The panel reports +whether the last Studio upload included files or was video only. If attaching +files fails, retry the upload or explicitly choose **Retry with video only**. + +When the video is ready, choose **Copy link**. Local edits do not automatically +replace the shared video: **Update shared version** uploads the saved project to +the same review page. Changes to access use a separate **Save access** action. +**Turn link off** keeps the project and comments; updating the video keeps an +off link off. Turning the link off does not free a shared-project slot. + +You can close the Share panel while sharing continues, but keep the local Studio +server running. Reopen the panel to recover progress, or use **Refresh** after a +connection problem. **Manage sharing** opens the web page for invites and owner +settings. Existing published project URLs continue to open separately. + +The local sharing bridge is available only from the same-origin loopback Studio +page. It does not expose CLI credentials or accept a different project path. +As with local preview, open projects whose scripts you trust. diff --git a/docs/packages/cli.mdx b/docs/packages/cli.mdx index 3d7588c0d6..b38858540d 100644 --- a/docs/packages/cli.mdx +++ b/docs/packages/cli.mdx @@ -3087,7 +3087,12 @@ 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. +a failure exit code. A failed processing or screening attempt stays failed across +CLI runs: `--status --json` returns `ok: false`, `state: "failed"`, an error, +and exit code 1. `previousUrl` keeps the earlier ready version available after a +failed update; `url` remains null. Use `--update` to explicitly retry with the +current project. Signing into a different account while a share is running +stops that operation; start it again after sign-in. The standard production CLI includes exact trusted storage origins for review videos and editable project sources; no upload configuration is required. diff --git a/packages/cli/scripts/build-copy.mjs b/packages/cli/scripts/build-copy.mjs index ee8798ed2d..2840596d10 100644 --- a/packages/cli/scripts/build-copy.mjs +++ b/packages/cli/scripts/build-copy.mjs @@ -104,6 +104,13 @@ async function main() { } mkdirSync(join(DIST, "commands"), { recursive: true }); + // The bundled sharing modules resolve their policy and Unicode tables beside + // the CLI chunks, rather than from the share package's source directory. + copyDir( + join(REPO_ROOT, "packages", "share", "src", "sources", "contract"), + join(DIST, "contract"), + ); + const studioDist = resolve(CLI_ROOT, "..", "studio", "dist"); await waitForStudioDist(studioDist); // Only the SPA studioServer.ts serves (index.html, /assets, /icons, /favicon.svg); diff --git a/packages/cli/src/cli.agentMode.test.ts b/packages/cli/src/cli.agentMode.test.ts index 63acedffce..64583c25e8 100644 --- a/packages/cli/src/cli.agentMode.test.ts +++ b/packages/cli/src/cli.agentMode.test.ts @@ -353,7 +353,9 @@ describe("agent-mode contract", () => { expect(run.code, run.stderr).toBe(1); expectJsonFailure(run, "runtime_error"); const { message } = JSON.parse(run.stdout).error as { message: string }; - expect(message).toMatch(/Aborting render due to lint issues in --strict mode: [1-9]\d* error/); + expect(message).toMatch(/Cannot render: [1-9]\d* error/); + expect(message).toContain("root_missing_dimensions"); + expect(message).toContain("Run hyperframes lint for details."); expect(run.stderr).toContain(message); }); diff --git a/packages/cli/src/commands/render/execute.test.ts b/packages/cli/src/commands/render/execute.test.ts index 9b63a17c2c..84de5acc3a 100644 --- a/packages/cli/src/commands/render/execute.test.ts +++ b/packages/cli/src/commands/render/execute.test.ts @@ -4,7 +4,12 @@ import { join } from "node:path"; import { afterEach, beforeEach, describe, expect, it, vi } from "vitest"; import type { ReferenceBackground } from "@hyperframes/producer"; import { createRenderPlan } from "./plan.js"; -import { batchRowRenderOptions, executeRenderPlan, renderOptionsFromPlan } from "./execute.js"; +import { + batchRowRenderOptions, + executeRenderPlan, + renderOptionsFromPlan, + runRenderLint, +} from "./execute.js"; import * as manager from "../../browser/manager.js"; import * as system from "../../telemetry/system.js"; import { wantsDesktopHint, type SingleRenderResult } from "../render.js"; @@ -188,3 +193,17 @@ describe("the machine result line after a single render", () => { expect(await resultLines({ renderTimeMs: 5 }, { docker: true })).toEqual([]); }); }); + +it("preserves actionable strict lint diagnostics for embedded sharing", async () => { + const dir = mkdtempSync(join(tmpdir(), "hf-render-invalid-")); + try { + writeFileSync( + join(dir, "index.html"), + '
', + ); + const plan = createRenderPlan({ dir, strict: true, quiet: true }); + await expect(runRenderLint(plan)).rejects.toThrow(/Cannot render:.*missing_timeline_registry/); + } finally { + rmSync(dir, { recursive: true, force: true }); + } +}); diff --git a/packages/cli/src/commands/render/execute.ts b/packages/cli/src/commands/render/execute.ts index 63f4352384..ad23f2bae8 100644 --- a/packages/cli/src/commands/render/execute.ts +++ b/packages/cli/src/commands/render/execute.ts @@ -14,7 +14,7 @@ import { } from "../../utils/lintProject.js"; import { normalizeErrorMessage } from "../../utils/errorMessage.js"; import { makeOutputFolder } from "../../utils/outputFolder.js"; -import { failCommand, setCommandExitCode } from "../../utils/commandResult.js"; +import { CliRuntimeError, failCommand, setCommandExitCode } from "../../utils/commandResult.js"; import { reportVariableIssues, resolveVariablesArg, @@ -302,8 +302,8 @@ export async function runRenderLint( ); presentRenderLintFindings(lintResult, plan.effectiveQuiet, plan.lintVerbose || willAbort); if (willAbort) { - presentRenderLintAbort(plan, lintResult, definitiveEntryMismatch); - failCommand(); + const message = presentRenderLintAbort(lintResult, definitiveEntryMismatch); + throw new CliRuntimeError(message, { presented: true }); } presentRenderLintContinuation(plan); } @@ -338,21 +338,17 @@ function presentRenderLintFindings( } function presentRenderLintAbort( - plan: RenderPlan, lintResult: ProjectLintResult, definitiveEntryMismatch: boolean, -): void { - const mode = plan.strictAll ? "--strict-all" : "--strict"; +): string { const counts = `${lintResult.totalErrors} error(s), ${lintResult.totalWarnings} warning(s)`; const findings = lintResult.results.flatMap((entry) => entry.result.findings); const first = findings.find((finding) => finding.severity === "error") ?? findings[0]; - errorBox( - definitiveEntryMismatch - ? "Aborting render because the default index.html entry is blank." - : `Aborting render due to lint issues in ${mode} mode: ${counts}`, - first ? `${first.code}: ${first.message}` : undefined, - "Run hyperframes lint for the full list.", - ); + const message = definitiveEntryMismatch + ? "Cannot render: the default index.html entry is blank." + : `Cannot render: ${counts}. ${first ? `${first.code}: ${first.message}` : "Fix the project lint issues."} Run hyperframes lint for details.`; + errorBox(message); + return message; } function presentRenderLintContinuation(plan: RenderPlan): void { diff --git a/packages/cli/src/commands/share.test.ts b/packages/cli/src/commands/share.test.ts new file mode 100644 index 0000000000..9e1acdcdb7 --- /dev/null +++ b/packages/cli/src/commands/share.test.ts @@ -0,0 +1,52 @@ +import { afterEach, beforeEach, expect, it, vi } from "vitest"; +import { runCommand } from "citty"; +import { consumeCommandResult } from "../utils/commandResult.js"; +const mocks = vi.hoisted(() => ({ run: vi.fn() })); +vi.mock("../utils/project.js", () => ({ resolveProjectOrThrow: () => ({ dir: "/project" }) })); +vi.mock("../share/service.js", () => ({ createShareService: () => ({ run: mocks.run }) })); +import command from "./share.js"; +beforeEach(() => { + consumeCommandResult(); + mocks.run.mockResolvedValue({ + state: "failed", + ready: false, + url: null, + previousUrl: "https://hyperframes.dev/r/previous", + manageUrl: "https://hyperframes.dev/shares", + source: { at: "not_checked" }, + version: { failure: "This video can't be shared." }, + }); +}); +afterEach(() => { + vi.restoreAllMocks(); + consumeCommandResult(); +}); +it("returns a failure envelope and the previous ready URL for a failed status", async () => { + const out = vi.spyOn(console, "log").mockImplementation(() => {}); + await runCommand(command, { rawArgs: ["--status", "--json"] }); + expect(consumeCommandResult().exitCode).toBe(1); + expect(out).toHaveBeenCalledOnce(); + expect(JSON.parse(String(out.mock.calls[0]?.[0]))).toMatchObject({ + ok: false, + state: "failed", + ready: false, + url: null, + previousUrl: "https://hyperframes.dev/r/previous", + error: { code: "share_export_failed", message: "This video can't be shared." }, + }); +}); +it("reports the failed attempt on stderr without calling the previous version ready", async () => { + const out = vi.spyOn(console, "log").mockImplementation(() => {}); + const err = vi.spyOn(console, "error").mockImplementation(() => {}); + await runCommand(command, { rawArgs: ["--status"] }); + expect(consumeCommandResult().exitCode).toBe(1); + expect(err).toHaveBeenCalledWith("This video can't be shared."); + expect(out).toHaveBeenCalledWith("Previous shared version: https://hyperframes.dev/r/previous"); + expect(out.mock.calls.flat().join(" ")).not.toContain("still processing"); +}); +it("still opens management when the latest export failed", async () => { + const out = vi.spyOn(console, "log").mockImplementation(() => {}); + await runCommand(command, { rawArgs: ["--manage", "--json"] }); + expect(consumeCommandResult().exitCode).toBe(0); + expect(JSON.parse(String(out.mock.calls[0]?.[0])).ok).toBe(true); +}); diff --git a/packages/cli/src/commands/share.ts b/packages/cli/src/commands/share.ts index 65e667f378..e32666b635 100644 --- a/packages/cli/src/commands/share.ts +++ b/packages/cli/src/commands/share.ts @@ -144,6 +144,14 @@ async function chooseAudience(input: ShareAction, args: ShareArgs, service: Shar async function presentResult(result: ShareState, input: ShareAction, json: boolean) { if (!json && result.source.at === "video_only") console.error(`Sharing video only (${result.source.reason}).`); + if (result.state === "failed" && input.action !== "manage") { + presentFailure(result, json); + return; + } + await presentSuccessfulResult(result, input, json); +} + +async function presentSuccessfulResult(result: ShareState, input: ShareAction, json: boolean) { if (json) console.log(JSON.stringify({ ok: true, ...result })); else if (input.action === "manage") { console.log(result.manageUrl); @@ -154,3 +162,14 @@ async function presentResult(result: ShareState, input: ShareAction, json: boole 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."); } + +function presentFailure(result: ShareState, json: boolean) { + const message = result.version.failure ?? "The shared video could not be processed."; + if (json) + console.log(JSON.stringify({ ...result, ...jsonFailure("share_export_failed", message) })); + else { + console.error(message); + if (result.previousUrl) console.log(`Previous shared version: ${result.previousUrl}`); + } + setCommandExitCode(1); +} diff --git a/packages/cli/src/server/shareBoundary.ts b/packages/cli/src/server/shareBoundary.ts new file mode 100644 index 0000000000..9765927696 --- /dev/null +++ b/packages/cli/src/server/shareBoundary.ts @@ -0,0 +1,31 @@ +import { randomBytes, timingSafeEqual } from "node:crypto"; + +export function localShareRequestAllowed(request: Request): boolean { + const host = request.headers.get("host"); + if (!host || request.headers.get("sec-fetch-site") !== "same-origin") return false; + try { + const local = new URL(`http://${host}`); + if (local.host !== host || !["localhost", "127.0.0.1", "[::1]"].includes(local.hostname)) + return false; + const origin = request.headers.get("origin"); + if (origin !== null) return origin === local.origin; + const referer = request.headers.get("referer"); + return referer !== null && new URL(referer).origin === local.origin; + } catch { + return false; + } +} + +export function createShareCsrf() { + const token = randomBytes(32).toString("base64url"); + return { + token, + accepts(value: string | null) { + return ( + value !== null && + Buffer.byteLength(value) === Buffer.byteLength(token) && + timingSafeEqual(Buffer.from(value), Buffer.from(token)) + ); + }, + }; +} diff --git a/packages/cli/src/server/shareEvents.ts b/packages/cli/src/server/shareEvents.ts new file mode 100644 index 0000000000..e3a650458e --- /dev/null +++ b/packages/cli/src/server/shareEvents.ts @@ -0,0 +1,12 @@ +import type { LocalShareInteraction } from "@hyperframes/studio-server"; + +export function shareEventInput(value: unknown): LocalShareInteraction | null { + if (typeof value !== "object" || value === null || Array.isArray(value)) return null; + if (Object.keys(value).length !== 2 || !("event" in value)) return null; + if (value.event === "share_link_copied" && "via" in value && value.via === "copy") + return { event: value.event, via: "copy" }; + if (value.event !== "share_opened" || !("link" in value)) return null; + const link = ["none", "live", "changed"] as const; + const chosen = link.find((item) => item === value.link); + return chosen ? { event: value.event, link: chosen } : null; +} diff --git a/packages/cli/src/server/shareFreshness.test.ts b/packages/cli/src/server/shareFreshness.test.ts new file mode 100644 index 0000000000..1271993300 --- /dev/null +++ b/packages/cli/src/server/shareFreshness.test.ts @@ -0,0 +1,74 @@ +import { mkdtempSync, mkdirSync, realpathSync, rmSync, writeFileSync } from "node:fs"; +import { tmpdir } from "node:os"; +import { dirname, join } from "node:path"; +import { afterEach, expect, it } from "vitest"; +import { shareContentFingerprint } from "../share/render.js"; +import type { ShareState } from "../share/service.js"; +import { presentPortableShare } from "./shareFreshness.js"; +const dirs: string[] = []; +afterEach(() => { + for (const dir of dirs.splice(0)) rmSync(dir, { recursive: true, force: true }); +}); +const state: ShareState = { + share: { + projectId: "project", + url: "https://hyperframes.dev/r/test", + access: "private", + role: "viewer", + commentsOn: true, + space: null, + elsewhere: false, + held: false, + }, + source: { + at: "ready", + snapshot: { space_id: "space", composition_id: "composition", snapshot_id: "snapshot" }, + }, + version: { + last: { exportedAt: "2026-11-06T00:00:00Z", current: true }, + source: "ready", + exporting: null, + failure: null, + }, + pending: null, + state: "ready", + ready: true, + url: "https://hyperframes.dev/r/test", + previousUrl: null, + manageUrl: "https://hyperframes.dev/shares", +}; +it.each([".media/voice.mp3", ".hyperframes/studio-manual-edits.json"])( + "detects %s edits even while the Desktop watcher still says current", + async (path) => { + const dir = realpathSync(mkdtempSync(join(tmpdir(), "hf-studio-freshness-"))); + dirs.push(dir); + writeFileSync(join(dir, "index.html"), ''); + mkdirSync(dirname(join(dir, path)), { recursive: true }); + writeFileSync(join(dir, path), "original"); + const contentFingerprint = (await shareContentFingerprint(dir))!; + let checksum = "uploaded-video"; + const deps = { + render: () => ({ + id: "render", + path: "video.mp4", + fingerprint: "watcher", + contentFingerprint, + }), + fingerprint: shareContentFingerprint, + uploaded: async () => ({ + projectId: "project", + exportedAt: "2026-11-06T00:00:00Z", + fingerprint: "watcher", + versionId: "version", + checksum: "uploaded-video", + }), + checksum: async () => checksum, + }; + expect((await presentPortableShare(dir, state, deps)).changed).toBeNull(); + writeFileSync(join(dir, path), "changed"); + expect((await presentPortableShare(dir, state, deps)).changed).toBe(true); + // Another command replaced the render pointer while the original video uploaded. + checksum = "different-video"; + expect((await presentPortableShare(dir, state, deps)).changed).toBeNull(); + }, +); diff --git a/packages/cli/src/server/shareFreshness.ts b/packages/cli/src/server/shareFreshness.ts new file mode 100644 index 0000000000..ff2d27a524 --- /dev/null +++ b/packages/cli/src/server/shareFreshness.ts @@ -0,0 +1,44 @@ +import { fileSha256Base64, versionOnPage } from "@hyperframes/share"; +import type { ShareState } from "../share/service.js"; +import { latestShareRender, shareContentFingerprint } from "../share/render.js"; +import { presentShare } from "./sharePresentation.js"; + +const dependencies = { + render: latestShareRender, + fingerprint: shareContentFingerprint, + uploaded: versionOnPage, + checksum: fileSha256Base64, +}; + +export async function presentPortableShare( + projectDir: string, + state: ShareState, + deps = dependencies, +) { + const result = presentShare(state); + try { + const render = deps.render(projectDir); + if (!render?.contentFingerprint) return result; + const last = await deps.uploaded(projectDir); + if (!matchesUpload(state, last)) return result; + if ((await deps.checksum(render.path)) !== last.checksum) return result; + const current = await deps.fingerprint(projectDir); + // Equal video bytes do not prove equal source inputs (for example metadata-only edits). + // Until exports persist the portable digest, only report known changes, never "clean". + result.changed = current && current !== render.contentFingerprint ? true : null; + } catch { + // Missing local artifacts cannot establish freshness of the published video. + } + return result; +} + +function matchesUpload( + state: ShareState, + last: Awaited>, +): last is NonNullable { + return Boolean( + last?.checksum && + last.projectId === state.share?.projectId && + last.exportedAt === state.version.last?.exportedAt, + ); +} diff --git a/packages/cli/src/server/sharePresentation.test.ts b/packages/cli/src/server/sharePresentation.test.ts new file mode 100644 index 0000000000..987bae7334 --- /dev/null +++ b/packages/cli/src/server/sharePresentation.test.ts @@ -0,0 +1,22 @@ +import { expect, it, vi } from "vitest"; +import { presentSpaces } from "./sharePresentation.js"; +vi.mock("../share/auth.js", () => ({ shareSite: () => "https://hyperframes.dev" })); + +it.each(["free", "subscribed", undefined] as const)( + "preserves authoritative plan %s for the upgrade offer", + (plan) => { + const space = { + space_id: "space", + name: "Workspace", + kind: "personal", + bound: true, + can_create_review: true, + review_entitlements: plan + ? { plan, project_limit: plan === "free" ? 5 : null, projects_used_up_to_limit: 2 } + : null, + } as Parameters[0][number]; + const [result] = presentSpaces([space]); + expect(result?.plan).toBe(plan ?? null); + expect(result?.upgradeUrl).toBe(plan === "free" ? "https://hyperframes.dev/pricing" : null); + }, +); diff --git a/packages/cli/src/server/sharePresentation.ts b/packages/cli/src/server/sharePresentation.ts new file mode 100644 index 0000000000..671cdbb239 --- /dev/null +++ b/packages/cli/src/server/sharePresentation.ts @@ -0,0 +1,59 @@ +import type { LocalShareSpace, LocalShareState } from "@hyperframes/studio-server"; +import { shareSite } from "../share/auth.js"; +import type { ShareService, ShareState } from "../share/service.js"; + +export function presentShare(value: ShareState): LocalShareState { + const held = + value.share?.held || + value.share?.takedown || + value.share?.sharingState?.state === "subscription_required"; + return { + state: presentedState(value, Boolean(held)), + url: held ? null : (value.url ?? value.previousUrl), + failure: value.state === "failed" ? value.version.failure : null, + hasReadyVersion: value.ready || Boolean(value.previousUrl), + manageUrl: value.manageUrl, + // Desktop's watcher does not cover every portable render input. + changed: knownChanges(value), + audience: value.share?.access ?? null, + spaceId: value.share?.space?.id ?? null, + source: value.source.at, + }; +} + +export function presentSpaces( + spaces: Awaited>, +): LocalShareSpace[] { + return spaces.map((space) => ({ + id: space.space_id, + name: space.name || (space.kind === "personal" ? "Personal workspace" : space.space_id), + bound: space.bound === true, + canCreate: space.can_create_review, + ...planOffer(space.review_entitlements), + audiences: [ + "private", + ...(space.review_entitlements?.allowed_collaborative_access_modes ?? []), + ], + used: space.review_entitlements?.projects_used_up_to_limit ?? null, + limit: space.review_entitlements?.project_limit ?? null, + })); +} + +function knownChanges(value: ShareState): boolean | null { + if (!value.share) return false; + return value.version.last && !value.version.last.current ? true : null; +} + +function planOffer( + entitlements: Awaited>[number]["review_entitlements"], +) { + const plan = entitlements?.plan ?? null; + return { plan, upgradeUrl: plan === "free" ? `${shareSite()}/pricing` : null }; +} + +function presentedState(value: ShareState, held: boolean): LocalShareState["state"] { + if (held) return "unavailable"; + if (value.state === "failed" || value.state === "not_shared" || value.state === "link_off") + return value.state; + return value.ready ? "ready" : "processing"; +} diff --git a/packages/cli/src/server/shareRoutes.test.ts b/packages/cli/src/server/shareRoutes.test.ts new file mode 100644 index 0000000000..447ae3015c --- /dev/null +++ b/packages/cli/src/server/shareRoutes.test.ts @@ -0,0 +1,427 @@ +import { describe, expect, it, vi } from "vitest"; +import { Hono } from "hono"; +import type { ShareService, ShareState } from "../share/service.js"; +import { mountShareRoutes } from "./shareRoutes.js"; +import { ReviewFailed } from "@hyperframes/share"; +import { AuthError } from "../auth/errors.js"; +import { createShareCsrf, localShareRequestAllowed } from "./shareBoundary.js"; + +const state: ShareState = { + source: { at: "not_checked" }, + share: null, + version: { last: null, source: "none", exporting: null, failure: null }, + pending: null, + state: "not_shared", + ready: false, + url: null, + previousUrl: null, + manageUrl: "https://hyperframes.dev/shares", +}; +function fixture() { + const service: ShareService = { + checkSession: vi.fn(async () => ({ + token: "secret", + owner: "owner", + heygen: "https://heygen.com", + heygenApi: "https://api.heygen.com", + })), + status: vi.fn(async () => state), + run: vi.fn(async () => state), + spaces: vi.fn(async () => []), + capabilities: vi.fn(async () => ({ versionSharing: true, shareFiles: false })), + setAccess: vi.fn(async () => state), + linkOff: vi.fn(async () => state), + linkOn: vi.fn(async () => state), + }; + const app = new Hono(); + const create = vi.fn(async () => service); + const login = vi.fn(async () => {}); + const track = vi.fn(); + mountShareRoutes(app, "/fixed/project", create, login, track); + return { app, service, create, login, track }; +} +const headers = { + host: "localhost:3000", + origin: "http://localhost:3000", + "sec-fetch-site": "same-origin", +}; +async function token(app: Hono) { + const response = await app.request("/api/share/bootstrap", { headers }); + expect(response.status).toBe(200); + const body: unknown = await response.json(); + if (!body || typeof body !== "object" || !("csrf" in body) || typeof body.csrf !== "string") + throw new Error("missing token"); + return body.csrf; +} +function request(app: Hono, path: string, csrf: string, body?: unknown) { + return app.request(`/api/share/${path}`, { + method: body ? "POST" : "GET", + headers: { ...headers, "x-hyperframes-share-csrf": csrf, "content-type": "application/json" }, + ...(body ? { body: JSON.stringify(body) } : {}), + }); +} +describe("local share boundary", () => { + it.each([ + { ...headers, host: "evil.example" }, + { ...headers, origin: "https://evil.example" }, + { ...headers, "sec-fetch-site": "cross-site" }, + { ...headers, "sec-fetch-site": "none" }, + { host: headers.host }, + { ...headers, host: "192.168.1.2:3000", origin: "http://192.168.1.2:3000" }, + { ...headers, host: "localhost:3000@evil.example" }, + ])("denies foreign, LAN and missing-origin requests before authentication %j", async (input) => { + const { app, create } = fixture(); + expect((await app.request("/api/share/bootstrap", { headers: input })).status).toBe(403); + expect(create).not.toHaveBeenCalled(); + }); + it("allows same-origin browser GET Referer and IPv6 loopback", () => { + expect( + localShareRequestAllowed( + new Request("http://localhost:3000/api/share/bootstrap", { + headers: { + host: headers.host, + referer: "http://localhost:3000/?project=x", + "sec-fetch-site": "same-origin", + }, + }), + ), + ).toBe(true); + expect( + localShareRequestAllowed( + new Request("http://[::1]:3000/api/share/bootstrap", { + headers: { + host: "[::1]:3000", + origin: "http://[::1]:3000", + "sec-fetch-site": "same-origin", + }, + }), + ), + ).toBe(true); + }); + it("guards reads and mutations with a separate token for each server", async () => { + const one = fixture(), + two = fixture(); + const csrf = await token(one.app); + for (const [path, body] of [ + ["snapshot", undefined], + ["jobs/x", undefined], + ["actions", { action: "off" }], + ] as const) { + expect((await request(one.app, path, "", body)).status).toBe(403); + expect((await request(two.app, path, csrf, body)).status).toBe(403); + } + expect((await request(one.app, "snapshot", csrf)).status).toBe(200); + expect(one.create).toHaveBeenCalledWith("/fixed/project", expect.any(Function)); + expect(two.create).not.toHaveBeenCalled(); + const guard = createShareCsrf(); + expect(guard.accepts("💜".repeat(43))).toBe(false); + }); +}); +it("requires explicit first audience and refuses arbitrary project paths", async () => { + const { app, service } = fixture(); + const csrf = await token(app); + for (const body of [ + { action: "share" }, + { action: "share", audience: "public", projectPath: "/other" }, + { action: "share", audience: "public", space: "../other" }, + { action: "remove" }, + ]) { + expect((await request(app, "actions", csrf, body)).status).toBe(400); + } + expect(service.run).not.toHaveBeenCalled(); +}); +it("keeps one server job alive after the request completes and recovers it on reopening", async () => { + const { app, service } = fixture(); + const csrf = await token(app); + let finish: (value: ShareState) => void = () => {}; + vi.mocked(service.run).mockImplementation( + () => + new Promise((resolve) => { + finish = resolve; + }), + ); + const response = await request(app, "actions", csrf, { + action: "share", + audience: "private", + space: "team1", + videoOnly: undefined, + }); + expect(response.status).toBe(202); + const started = await response.json(); + expect(started.state).toBe("running"); + expect((await request(app, "actions", csrf, { action: "update" })).status).toBe(409); + expect((await (await request(app, "snapshot", csrf)).json()).job.id).toBe(started.id); + finish(state); + await vi.waitFor(async () => + expect((await (await request(app, `jobs/${started.id}`, csrf)).json()).state).toBe("done"), + ); + expect(service.run).toHaveBeenCalledOnce(); + expect(service.run).toHaveBeenCalledWith({ + action: "share", + audience: "private", + space: "team1", + videoOnly: undefined, + }); +}); +it("returns failed jobs without changing access or retrying automatically", async () => { + const { app, service } = fixture(); + const csrf = await token(app); + vi.mocked(service.run).mockRejectedValue(new Error("Render failed")); + await request(app, "actions", csrf, { action: "update" }); + await vi.waitFor(async () => + expect((await (await request(app, "snapshot", csrf)).json()).job.error.message).toBe( + "Render failed", + ), + ); + expect(service.linkOn).not.toHaveBeenCalled(); + expect(service.setAccess).not.toHaveBeenCalled(); +}); +it.each(["off", "on", "access"] as const)( + "routes explicit %s management without starting an upload", + async (action) => { + const { app, service } = fixture(); + const csrf = await token(app); + await request(app, "actions", csrf, { + action, + ...(action === "access" ? { audience: "invite" } : {}), + }); + await vi.waitFor(() => + expect( + action === "off" ? service.linkOff : action === "on" ? service.linkOn : service.setAccess, + ).toHaveBeenCalledOnce(), + ); + expect(service.run).not.toHaveBeenCalled(); + }, +); + +it("runs one browser sign-in job without returning credentials and verifies identity afterward", async () => { + const { app, service, login, create } = fixture(); + const csrf = await token(app); + vi.mocked(service.status).mockRejectedValue(new AuthError("UNAUTHENTICATED", "Sign in first")); + let finish = () => {}; + login.mockImplementation( + () => + new Promise((resolve) => { + finish = resolve; + }), + ); + const started = await (await request(app, "actions", csrf, { action: "login" })).json(); + expect(started.step).toBe("signing_in"); + expect((await request(app, "actions", csrf, { action: "login" })).status).toBe(409); + const reopening = await (await request(app, "snapshot", csrf)).json(); + expect(reopening.code).toBe("unauthenticated"); + expect(reopening.job.id).toBe(started.id); + vi.mocked(service.status).mockResolvedValue(state); + finish(); + await vi.waitFor(async () => + expect((await (await request(app, `jobs/${started.id}`, csrf)).json()).state).toBe("done"), + ); + expect(login).toHaveBeenCalledOnce(); + expect(create).toHaveBeenCalledTimes(2); + const complete = await (await request(app, "snapshot", csrf)).json(); + expect(JSON.stringify(complete)).not.toMatch(/access_token|refresh_token|authorize_url/); + expect(service.run).not.toHaveBeenCalled(); +}); +it("passes explicit video-only recovery and rejects nonboolean bypass values", async () => { + const { app, service } = fixture(); + const csrf = await token(app); + expect( + (await request(app, "actions", csrf, { action: "update", videoOnly: "true" })).status, + ).toBe(400); + await request(app, "actions", csrf, { action: "update", videoOnly: true }); + await vi.waitFor(() => + expect(service.run).toHaveBeenCalledWith({ + action: "update", + audience: undefined, + space: undefined, + videoOnly: true, + }), + ); +}); + +it("requires the same boundary for events and never forwards arbitrary properties", async () => { + const { app, track } = fixture(); + const csrf = await token(app); + expect((await request(app, "events", "", { event: "share_opened", link: "live" })).status).toBe( + 403, + ); + expect( + (await request(app, "events", csrf, { event: "share_opened", link: "live", url: "secret" })) + .status, + ).toBe(400); + expect( + (await request(app, "events", csrf, { event: "share_link_copied", via: "update" })).status, + ).toBe(400); + expect( + (await request(app, "events", csrf, { event: "share_opened", link: "changed" })).status, + ).toBe(204); + expect(track).toHaveBeenCalledExactlyOnceWith( + { event: "share_opened", link: "changed" }, + "local_studio", + ); +}); + +it("rejects stale actions and job reads after logout without returning the previous result", async () => { + const { app, service } = fixture(); + const csrf = await token(app); + const started = await (await request(app, "actions", csrf, { action: "update" })).json(); + await vi.waitFor(async () => + expect((await (await request(app, `jobs/${started.id}`, csrf)).json()).state).toBe("done"), + ); + const signedOut = new AuthError("UNAUTHENTICATED", "Sign in first"); + vi.mocked(service.checkSession).mockRejectedValue(signedOut); + vi.mocked(service.status).mockRejectedValue(signedOut); + for (const [path, action] of [ + [`jobs/${started.id}`, undefined], + ["snapshot", undefined], + ["actions", { action: "off" }], + ] as const) { + const response = await request(app, path, csrf, action); + expect(response.status).toBe(400); + const body = await response.json(); + expect(body.code).toBe("unauthenticated"); + expect(body.result).toBeUndefined(); + expect(body.job ?? null).toBeNull(); + } + expect(service.linkOff).not.toHaveBeenCalled(); +}); + +it("does not reveal another account's completed job to a newly opened panel", async () => { + const { app, service } = fixture(); + const first = await token(app); + const started = await (await request(app, "actions", first, { action: "update" })).json(); + await vi.waitFor(async () => + expect((await (await request(app, `jobs/${started.id}`, first)).json()).state).toBe("done"), + ); + vi.mocked(service.checkSession).mockResolvedValue({ + token: "other-secret", + owner: "other", + heygen: "https://heygen.com", + heygenApi: "https://api.heygen.com", + }); + const second = await token(app); + expect(second).not.toBe(first); + expect((await request(app, `jobs/${started.id}`, second)).status).toBe(404); + expect((await (await request(app, "snapshot", second)).json()).job).toBeNull(); +}); + +it("serializes actions even when concurrent requests await identity verification", async () => { + const { app, service } = fixture(); + const csrf = await token(app); + let verify = () => {}; + const barrier = new Promise((resolve) => { + verify = resolve; + }); + vi.mocked(service.checkSession).mockImplementation(async () => { + await barrier; + return { + token: "secret", + owner: "owner", + heygen: "https://heygen.com", + heygenApi: "https://api.heygen.com", + }; + }); + let finish = () => {}; + vi.mocked(service.run).mockImplementation( + () => + new Promise((resolve) => { + finish = () => resolve(state); + }), + ); + const requests = [ + request(app, "actions", csrf, { action: "update" }), + request(app, "actions", csrf, { action: "update" }), + ]; + await vi.waitFor(() => expect(service.checkSession).toHaveBeenCalledTimes(2)); + verify(); + expect((await Promise.all(requests)).map((response) => response.status).sort()).toEqual([ + 202, 409, + ]); + expect(service.run).toHaveBeenCalledOnce(); + finish(); +}); + +it("withholds an in-flight result when the account changes before completion", async () => { + const { app, service } = fixture(); + const csrf = await token(app); + let finish = () => {}; + vi.mocked(service.run).mockImplementation( + () => + new Promise((resolve) => { + finish = () => resolve(state); + }), + ); + const started = await (await request(app, "actions", csrf, { action: "update" })).json(); + vi.mocked(service.checkSession).mockRejectedValue( + new AuthError("LOGIN_CHANGED", "Login changed"), + ); + finish(); + await vi.waitFor(async () => { + const response = await request(app, `jobs/${started.id}`, csrf); + expect(response.status).toBe(400); + expect(await response.json()).toEqual({ code: "login_changed", message: "Login changed" }); + }); +}); + +it.each(["login_required", "", "invalid_token"])( + "exposes browser sign-in recovery for a review 401 (%s)", + async (reason) => { + const { app, service, login } = fixture(); + const csrf = await token(app); + vi.mocked(service.status).mockRejectedValue(new ReviewFailed(401, reason)); + vi.mocked(service.checkSession).mockRejectedValueOnce( + new AuthError("LOGIN_EXPIRED", "Your sign-in has expired. Sign in again."), + ); + const response = await request(app, "snapshot", csrf); + expect(response.status).toBe(400); + expect(await response.json()).toMatchObject({ + code: "login_expired", + message: expect.stringContaining("Sign in again"), + }); + expect(login).not.toHaveBeenCalled(); + vi.mocked(service.status).mockResolvedValue(state); + const started = await (await request(app, "actions", csrf, { action: "login" })).json(); + await vi.waitFor(async () => + expect((await (await request(app, `jobs/${started.id}`, csrf)).json()).state).toBe("done"), + ); + expect(login).toHaveBeenCalledOnce(); + }, +); + +it("preserves admission failures instead of offering an expired-session retry", async () => { + const { app, service, login } = fixture(); + const csrf = await token(app); + vi.mocked(service.status).mockRejectedValue(new ReviewFailed(403, "feature_unavailable")); + const response = await request(app, "snapshot", csrf); + expect(await response.json()).toMatchObject({ code: "feature_unavailable" }); + expect(login).not.toHaveBeenCalled(); +}); + +it("distinguishes review admission refusal only after fresh account validation", async () => { + const { app, service, login } = fixture(); + const csrf = await token(app); + vi.mocked(service.status).mockRejectedValue(new ReviewFailed(401, "login_required")); + const response = await request(app, "snapshot", csrf); + expect(await response.json()).toMatchObject({ + code: "sharing_not_admitted", + message: expect.stringContaining("You're signed in"), + }); + expect(service.checkSession).toHaveBeenCalledWith(true); + expect(login).not.toHaveBeenCalled(); +}); + +it("shows a completed login's admission failure to its initiating panel", async () => { + const { app, service } = fixture(); + const csrf = await token(app); + vi.mocked(service.status).mockRejectedValue(new ReviewFailed(401, "login_required")); + const started = await (await request(app, "actions", csrf, { action: "login" })).json(); + await vi.waitFor(async () => { + const response = await request(app, `jobs/${started.id}`, csrf); + expect(response.status).toBe(200); + expect(await response.json()).toMatchObject({ + state: "failed", + result: null, + error: { code: "sharing_not_admitted" }, + }); + }); +}); diff --git a/packages/cli/src/server/shareRoutes.ts b/packages/cli/src/server/shareRoutes.ts new file mode 100644 index 0000000000..ff86ea8ec2 --- /dev/null +++ b/packages/cli/src/server/shareRoutes.ts @@ -0,0 +1,262 @@ +import { randomUUID } from "node:crypto"; +import { Hono } from "hono"; +import { bodyLimit } from "hono/body-limit"; +import type { + LocalShareAction, + LocalShareAudience, + LocalShareJob, + LocalShareSnapshot, +} from "@hyperframes/studio-server"; +import { ReviewFailed, type ReviewExportProgress } from "@hyperframes/share"; +import type { ShareService } from "../share/service.js"; +import { shareError } from "../share/errors.js"; +import { localShareRequestAllowed } from "./shareBoundary.js"; +import { trackShareInteraction } from "../share/telemetry.js"; +import { shareEventInput } from "./shareEvents.js"; +import { presentSpaces } from "./sharePresentation.js"; + +import { createShareSessions, shareSessionKey } from "./shareSessions.js"; + +import { presentPortableShare } from "./shareFreshness.js"; + +const AUDIENCES: readonly LocalShareAudience[] = ["public", "team", "invite", "private"]; +function actionInput(value: unknown): LocalShareAction | null { + if (!isRecord(value)) return null; + const record = Object.fromEntries(Object.entries(value)); + if ( + Object.keys(record).some((key) => !["action", "audience", "space", "videoOnly"].includes(key)) + ) + return null; + const { action, audience, space, videoOnly } = record; + if (!isAction(action)) return null; + const chosen = AUDIENCES.find((mode) => mode === audience); + if (audience !== undefined && !chosen) return null; + const options = actionOptions(space, videoOnly); + if (!options) return null; + if (["share", "access"].includes(action) && !chosen) return null; + return { + action, + audience: chosen, + ...options, + }; +} + +function isRecord(value: unknown): value is Record { + return typeof value === "object" && value !== null && !Array.isArray(value); +} + +function isAction(value: unknown): value is LocalShareAction["action"] { + return ["share", "update", "access", "off", "on", "login"].some((action) => action === value); +} +function actionOptions( + space: unknown, + videoOnly: unknown, +): Pick | null { + if (!validSpace(space)) return null; + if (videoOnly !== undefined && typeof videoOnly !== "boolean") return null; + const options: Pick = {}; + if (typeof space === "string") options.space = space; + if (videoOnly === true) options.videoOnly = true; + return options; +} +function validSpace(value: unknown): boolean { + return value === undefined || (typeof value === "string" && /^[A-Za-z0-9_-]{1,128}$/.test(value)); +} + +type CreateService = ( + path: string, + progress: (value: ReviewExportProgress | null) => void, +) => Promise; +const defaultCreate: CreateService = async (path, progress) => + (await import("../share/service.js")).createShareService(path, progress, { + surface: "local_studio", + pinIdentity: true, + }); + +async function defaultLogin(): Promise { + const { startAuthorizationCodeFlow } = await import("../auth/oauth.js"); + await startAuthorizationCodeFlow({ timeoutMs: 300_000 }); +} + +export function mountShareRoutes( + app: Hono, + projectDir: string, + create: CreateService = defaultCreate, + login: () => Promise = defaultLogin, + track: typeof trackShareInteraction = trackShareInteraction, +): void { + const routes = new Hono(); + let job: LocalShareJob | null = null; + const hasRunningJob = () => job?.state === "running"; + let jobOwner: string | null = null; + let loginToken: string | null = null; + const sessions = createShareSessions(() => + create(projectDir, (progress) => { + if (job?.state === "running" && progress) job.step = progress.step; + }), + ); + const visibleJob = async (token: string) => { + if (loginToken === token && job && job.state !== "done") return job; + const session = sessions.get(token); + if (!session) return null; + const key = shareSessionKey(await (await session.get()).checkSession()); + return key === jobOwner ? job : null; + }; + routes.use("*", async (c, next) => { + c.header("Cache-Control", "no-store"); + if (!localShareRequestAllowed(c.req.raw)) + return c.json({ code: "forbidden", message: "Open sharing from this local Studio." }, 403); + if ( + c.req.path !== "/api/share/bootstrap" && + !sessions.get(c.req.header("x-hyperframes-share-csrf") ?? "") + ) + return c.json({ code: "forbidden", message: "Refresh Studio to reconnect sharing." }, 403); + return next(); + }); + routes.use("*", bodyLimit({ maxSize: 4096 })); + routes.get("/bootstrap", (c) => c.json({ csrf: sessions.open() })); + routes.post("/events", async (c) => { + const event = shareEventInput(await c.req.json().catch(() => null)); + if (!event) return c.json({ code: "invalid_event", message: "Unknown sharing event." }, 400); + track(event, "local_studio"); + return c.body(null, 204); + }); + routes.get("/snapshot", async (c) => { + try { + const sharing = await sessions.get(c.req.header("x-hyperframes-share-csrf")!)!.get(); + const [state, spaces, capabilities] = await Promise.all([ + sharing.status(), + sharing.spaces(), + sharing.capabilities(), + ]); + return c.json({ + versionSharing: capabilities.versionSharing, + share: await presentPortableShare(projectDir, state), + spaces: presentSpaces(spaces), + job: await visibleJob(c.req.header("x-hyperframes-share-csrf")!), + } satisfies LocalShareSnapshot); + } catch (error) { + return c.json( + { + ...(await presentError(error, c.req.header("x-hyperframes-share-csrf")!)), + job: + loginToken === c.req.header("x-hyperframes-share-csrf") && job && job.state !== "done" + ? job + : null, + }, + 400, + ); + } + }); + routes.get("/jobs/:id", async (c) => { + try { + const current = await visibleJob(c.req.header("x-hyperframes-share-csrf")!); + return current?.id === c.req.param("id") + ? c.json(current) + : c.json( + { code: "job_not_found", message: "Refresh sharing to see the current state." }, + 404, + ); + } catch (error) { + return c.json(await presentError(error, c.req.header("x-hyperframes-share-csrf")!), 400); + } + }); + routes.post("/actions", async (c) => { + const input = actionInput(await c.req.json().catch(() => null)); + if (!input) + return c.json( + { code: "invalid_action", message: "Choose a valid sharing action and audience." }, + 400, + ); + const token = c.req.header("x-hyperframes-share-csrf")!; + const session = sessions.get(token)!; + if (hasRunningJob()) + return c.json( + { + code: "share_busy", + message: "Sharing is already in progress.", + job: await visibleJob(token).catch(() => null), + }, + 409, + ); + let owner: string | null = null; + if (input.action !== "login") { + try { + owner = await sessionOwner(session); + } catch (error) { + return c.json(await presentError(error, c.req.header("x-hyperframes-share-csrf")!), 400); + } + } + if (hasRunningJob()) + return c.json({ code: "share_busy", message: "Sharing is already in progress." }, 409); + jobOwner = owner; + loginToken = input.action === "login" ? token : null; + const current: LocalShareJob = { + id: randomUUID(), + state: "running", + step: actionStep(input), + result: null, + error: null, + }; + job = current; + void runJob(current, input, session, token); + return c.json(current, 202); + }); + async function runJob( + current: LocalShareJob, + input: LocalShareAction, + session: NonNullable>, + token: string, + ) { + try { + if (input.action === "login") { + await login(); + session.reset(); + } + const sharing = await session.get(); + const result = await executeAction(sharing, input); + jobOwner = shareSessionKey(await sharing.checkSession()); + current.result = await presentPortableShare(projectDir, result); + current.state = "done"; + } catch (error) { + current.error = await presentError(error, token); + current.state = "failed"; + } + } + async function presentError(error: unknown, token: string) { + if (!(error instanceof ReviewFailed) || error.status !== 401) return shareError(error); + const session = sessions.get(token); + if (!session) return shareError(error); + try { + await (await session.get()).checkSession(true); + return { + code: "sharing_not_admitted", + message: + "You're signed in, but sharing isn't accepting this sign-in. Try again later or contact support.", + }; + } catch (verificationError) { + return shareError(verificationError); + } + } + app.route("/api/share", routes); +} + +function executeAction(sharing: ShareService, input: LocalShareAction) { + if (input.action === "login") return sharing.status(); + if (input.action === "access" && input.audience) return sharing.setAccess(input.audience); + if (input.action === "off") return sharing.linkOff(); + if (input.action === "on") return sharing.linkOn(); + return sharing.run({ + action: input.action === "update" ? "update" : "share", + audience: input.audience, + space: input.space, + videoOnly: input.videoOnly, + }); +} + +function actionStep(input: LocalShareAction) { + return input.action === "login" ? "signing_in" : "preparing"; +} +async function sessionOwner(session: { get: () => Promise }) { + return shareSessionKey(await (await session.get()).checkSession()); +} diff --git a/packages/cli/src/server/shareSessions.ts b/packages/cli/src/server/shareSessions.ts new file mode 100644 index 0000000000..2b3e5f6318 --- /dev/null +++ b/packages/cli/src/server/shareSessions.ts @@ -0,0 +1,31 @@ +import type { ShareService } from "../share/service.js"; +import { createShareCsrf } from "./shareBoundary.js"; + +export function shareSessionKey(value: Awaited>) { + return JSON.stringify([value.owner, value.heygen, value.heygenApi]); +} + +export function createShareSessions(create: () => Promise) { + const sessions = new Map>(); + function session() { + let service: Promise | null = null; + return { + get: () => (service ??= create()), + reset: () => { + service = null; + }, + }; + } + return { + open() { + const token = createShareCsrf().token; + if (sessions.size >= 128) { + const oldest = sessions.keys().next().value; + if (oldest) sessions.delete(oldest); + } + sessions.set(token, session()); + return token; + }, + get: (token: string) => sessions.get(token), + }; +} diff --git a/packages/cli/src/server/studioServer.file-race.test.ts b/packages/cli/src/server/studioServer.file-race.test.ts index 384ce2b974..c6c3deebfe 100644 --- a/packages/cli/src/server/studioServer.file-race.test.ts +++ b/packages/cli/src/server/studioServer.file-race.test.ts @@ -253,6 +253,7 @@ describe("Studio bundle file reads", () => { const text = await response.text(); expect(text).toContain("Studio"); expect(text).toContain('"VITE_STUDIO_STATIC_TEST":"runtime-value"'); + expect(text).toContain(''); expectClosed(); }); diff --git a/packages/cli/src/server/studioServer.ts b/packages/cli/src/server/studioServer.ts index 7ded7537a6..72f732c043 100644 --- a/packages/cli/src/server/studioServer.ts +++ b/packages/cli/src/server/studioServer.ts @@ -36,6 +36,7 @@ import { import { emitStudioRenderComplete, emitStudioRenderError } from "./studioRenderTelemetry.js"; import { startRenderCpuSampler } from "../telemetry/renderCpu.js"; import { mountDesktopRoutes } from "./desktopRoutes.js"; +import { mountShareRoutes } from "./shareRoutes.js"; import { isDevMode } from "../utils/env.js"; import { insideHostApp } from "../utils/desktopApp.js"; import { runRenderSetupWorker } from "../utils/cancellableProcess.js"; @@ -1053,6 +1054,7 @@ export function createStudioServer(options: StudioServerOptions): StudioServer { }); mountDesktopRoutes(app, projectDir); + mountShareRoutes(app, projectDir); // ── Pre-flight checks for render ──────────────────────────────────────── // Intercept render requests before they reach the shared API so we can @@ -1197,9 +1199,10 @@ export function createStudioServer(options: StudioServerOptions): StudioServer { // (`HYPERFRAMES_PREVIEW_HOST=0.0.0.0`) needs it to stay in agreement with // the CLI. See buildStudioHeadScriptsForHost. const headScript = buildStudioHeadScriptsForHost(buildRuntimeEnvScript(), c.req.header("host")); - if (headScript) { - html = html.replace("", `${headScript}`); - } + html = html.replace( + "", + `${headScript}`, + ); // The shell names the current hashed bundle, so it always revalidates. // `no-cache` not `no-store`: same refetch without an ETag, but `no-store` // would blocklist the document from Chrome's bfcache. diff --git a/packages/cli/src/share/auth.test.ts b/packages/cli/src/share/auth.test.ts index ded5049539..031e05cad6 100644 --- a/packages/cli/src/share/auth.test.ts +++ b/packages/cli/src/share/auth.test.ts @@ -44,14 +44,14 @@ describe("share OAuth identity", () => { expect(mocks.refresh).toHaveBeenCalledWith("refresh"); expect(mocks.user).not.toHaveBeenCalled(); }); - it("resolves the actor again when the credential changes", async () => { + it("rejects a different actor 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"); + await expect(auth.access()).rejects.toMatchObject({ code: "LOGIN_CHANGED" }); }); it("does not retry a refused environment token", async () => { mocks.resolve.mockResolvedValue(oauth("refused")); @@ -61,3 +61,24 @@ describe("share OAuth identity", () => { expect(mocks.refresh).not.toHaveBeenCalled(); }); }); + +it("pins a Studio session across account switches but permits same-account token rotation", async () => { + const auth = createShareAccess(true); + mocks.resolve.mockResolvedValue(oauth("first")); + await auth.access(); + mocks.resolve.mockResolvedValue(oauth("refreshed")); + await expect(auth.access()).resolves.toMatchObject({ owner: "owner", token: "refreshed" }); + mocks.resolve.mockResolvedValue(oauth("other")); + mocks.user.mockResolvedValue({ username: "other" }); + await expect(auth.access()).rejects.toMatchObject({ code: "LOGIN_CHANGED" }); + await expect(auth.access()).rejects.toMatchObject({ code: "LOGIN_CHANGED" }); +}); + +it("can revalidate the same token instead of trusting a cached account", async () => { + mocks.resolve.mockResolvedValue(oauth("same")); + const auth = createShareAccess(true); + await auth.access(); + mocks.user.mockRejectedValue(new Error("account validation refused")); + await expect(auth.access(undefined, true)).rejects.toThrow("account validation refused"); + expect(mocks.user).toHaveBeenCalledTimes(2); +}); diff --git a/packages/cli/src/share/auth.ts b/packages/cli/src/share/auth.ts index 1dc82c5129..9bdd571b42 100644 --- a/packages/cli/src/share/auth.ts +++ b/packages/cli/src/share/auth.ts @@ -1,6 +1,6 @@ import { apiBaseUrl, AuthClient } from "../auth/client.js"; import { tokenEndpoint, oauthEnvironment } from "../auth/config.js"; -import { AuthError } from "../auth/errors.js"; +import { AuthError, ErrLoginChanged } from "../auth/errors.js"; import { refreshTokens } from "../auth/oauth.js"; import { resolveCredential } from "../auth/resolver.js"; @@ -8,25 +8,31 @@ export function shareSite(): string { return oauthEnvironment() === "dev" ? "https://dev.hyperframes.dev" : "https://hyperframes.dev"; } -export function createShareAccess() { +export function createShareAccess(pinIdentity = true) { + let bound: string | undefined; let identity: { token: string; owner: string; email: string | null } | undefined; const userClient = new AuthClient(); - const access = async (refused?: string) => { + const access = async (refused?: string, verifyIdentity = false) => { const credential = await shareCredential(refused); - if (identity?.token !== credential.access_token) { + let account = identity; + if (verifyIdentity || account?.token !== credential.access_token) { const user = await userClient.getCurrentUser(credential); if (!user.username) throw loginRequired(); - identity = { + account = { token: credential.access_token, owner: user.username, email: user.email ?? null, }; } + const key = JSON.stringify([account.owner, new URL(tokenEndpoint()).origin, apiBaseUrl()]); + if (pinIdentity && bound !== undefined && bound !== key) throw ErrLoginChanged(); + bound = key; + identity = account; return { token: credential.access_token, heygen: new URL(tokenEndpoint()).origin, heygenApi: apiBaseUrl(), - owner: identity.owner, + owner: account.owner, }; }; return { diff --git a/packages/cli/src/share/errors.ts b/packages/cli/src/share/errors.ts index 4b01dcd6d9..5a662c8089 100644 --- a/packages/cli/src/share/errors.ts +++ b/packages/cli/src/share/errors.ts @@ -30,7 +30,7 @@ export function shareError(error: unknown): { code: string; message: string } { }; if (error instanceof ReviewFailed) return { - code: error.reason || "share_failed", + code: error.status === 401 ? "login_expired" : error.reason || "share_failed", message: HINTS[error.reason] ?? reviewSentence(error), }; return { diff --git a/packages/cli/src/share/identity.test.ts b/packages/cli/src/share/identity.test.ts new file mode 100644 index 0000000000..6fa7295ffb --- /dev/null +++ b/packages/cli/src/share/identity.test.ts @@ -0,0 +1,73 @@ +import { beforeEach, expect, it, vi } from "vitest"; +const mocks = vi.hoisted(() => ({ + token: "first", + owner: "first-owner", + register: vi.fn(), + add: vi.fn(), + render: vi.fn(), +})); +vi.mock("../auth/resolver.js", () => ({ + resolveCredential: async () => ({ type: "oauth", access_token: mocks.token, refreshable: false }), +})); +vi.mock("../auth/client.js", () => ({ + apiBaseUrl: () => "https://api.heygen.com", + AuthClient: class { + getCurrentUser = async () => ({ username: mocks.owner }); + }, +})); +vi.mock("./host.js", () => ({ + bindCliShareProject: (path: string) => path, + assertReviewUploadStorage: () => {}, +})); +vi.mock("./render.js", () => ({ prepareShareRender: mocks.render })); +vi.mock("../telemetry/client.js", () => ({ trackEvent: vi.fn() })); +vi.mock("@hyperframes/share", async (original) => { + const actual = await original(); + return { + ...actual, + reviewClient: ({ access }: { access: () => Promise }) => ({ + access, + reviewFlags: async () => ({ versionSharing: true, shareFiles: false }), + spaces: async () => [ + { + space_id: "space", + bound: true, + can_create_review: true, + review_entitlements: { + can_register_project: true, + allowed_collaborative_access_modes: ["public"], + }, + }, + ], + project: async () => ({ latest_ready_version_id: "version" }), + }), + reviewStatus: async () => null, + reviewRecord: async () => null, + reviewVersion: async () => ({ last: null, source: "ready", failure: null }), + pendingReviewExport: async () => null, + refreshReviewExport: async () => {}, + shareForReview: async ({ client }: { client: { access: () => Promise } }) => { + await client.access(); + mocks.register(); + return { projectId: "project", space: { id: "space" }, access: "public" }; + }, + addVersion: mocks.add, + }; +}); +import { createShareService } from "./service.js"; +beforeEach(() => { + vi.clearAllMocks(); + mocks.token = "first"; + mocks.owner = "first-owner"; +}); +it("does not register or upload as a different account after rendering", async () => { + mocks.render.mockImplementation(async () => { + mocks.token = "second"; + mocks.owner = "second-owner"; + }); + await expect( + createShareService("/project").run({ action: "share", audience: "public" }), + ).rejects.toMatchObject({ code: "LOGIN_CHANGED" }); + expect(mocks.register).not.toHaveBeenCalled(); + expect(mocks.add).not.toHaveBeenCalled(); +}); diff --git a/packages/cli/src/share/service.test.ts b/packages/cli/src/share/service.test.ts index 6c755b83eb..4c253a36d3 100644 --- a/packages/cli/src/share/service.test.ts +++ b/packages/cli/src/share/service.test.ts @@ -388,3 +388,24 @@ it("link reactivation cannot bypass the first-share rollout gate", async () => { }); expect(mocks.create).not.toHaveBeenCalled(); }); + +it.each([null, "previous-version"])( + "keeps a terminal failure separate from ready version %s", + async (latest) => { + mocks.status.mockResolvedValue(shared); + mocks.project.mockResolvedValue({ latest_ready_version_id: latest }); + mocks.version.mockResolvedValue({ + last: null, + source: "ready", + failure: "This video can't be shared.", + }); + const result = await createShareService("/project").run({ action: "status" }); + expect(result).toMatchObject({ + state: "failed", + ready: false, + url: null, + previousUrl: latest ? shared.url : null, + }); + expect(mocks.add).not.toHaveBeenCalled(); + }, +); diff --git a/packages/cli/src/share/service.ts b/packages/cli/src/share/service.ts index 2ce16b3dd7..1f95a7457b 100644 --- a/packages/cli/src/share/service.ts +++ b/packages/cli/src/share/service.ts @@ -30,8 +30,9 @@ export interface ShareAction { waitSeconds?: number; videoOnly?: boolean; } -function linkState(share: ReviewShare | null, ready: boolean): string { +function linkState(share: ReviewShare | null, ready: boolean, failed: boolean): string { if (!share) return "not_shared"; + if (failed) return "failed"; if (!share.url) return "link_off"; return ready ? "ready" : "processing"; } @@ -60,15 +61,16 @@ async function readStatus( const pending = await pendingReviewExport(dir); const activeUrl = share?.url ?? null; const processing = isProcessing(pending, share); - const ready = Boolean(activeUrl && latest && !processing); + const failed = hasFailedVersion(version); + const ready = Boolean(activeUrl && latest && !processing && !failed); return { share, version, pending, - state: linkState(share, ready), + state: linkState(share, ready, failed), ready, source: uncheckedSource(), - ...statusLinks(activeUrl, ready, processing, project), + ...statusLinks(activeUrl, ready, processing || failed, project), }; } async function readProject(share: ReviewShare | null, client: ReviewClient) { @@ -158,10 +160,10 @@ function assertResumeSource(current: ShareState, input: ShareAction) { export function createShareService( projectPath: string, progress: (value: ReviewExportProgress | null) => void = () => {}, - options: { surface?: ShareSurface } = {}, + options: { surface?: ShareSurface; pinIdentity?: boolean } = {}, ) { const dir = bindCliShareProject(projectPath); - const auth = createShareAccess(); + const auth = createShareAccess(options.pinIdentity); const client = reviewClient(auth); const status = async (expectedProjectId?: string) => { await auth.access(); @@ -258,6 +260,7 @@ export function createShareService( return upload(input, target.projectId, sources, attempt); }; return { + checkSession: (verifyIdentity = false) => auth.access(undefined, verifyIdentity), status, run: (input: ShareAction) => input.action === "status" || input.action === "manage" @@ -284,3 +287,7 @@ export function createShareService( } export type ShareService = ReturnType; export type ShareState = Awaited>; + +function hasFailedVersion(version: Awaited>): boolean { + return Boolean(version.failure && !version.held); +} diff --git a/packages/share/src/reviewExport.mjs b/packages/share/src/reviewExport.mjs index 0fed421a97..bf7576c381 100644 --- a/packages/share/src/reviewExport.mjs +++ b/packages/share/src/reviewExport.mjs @@ -39,10 +39,10 @@ import { versionSentence } from "./reviewVersionSentences.mjs"; * definitive result; `reviewSent`: cleanup cutoff, with attribution only when the accepted attempt is * known; `last`: the newest version. * @typedef {{ pending: { body: ExportRequest, videoId: string | null, projectId?: string | null, - * checkingSince?: number, snapshotRefused?: boolean, unanswered?: boolean, reviewSent?: ReviewSent } | null, + * renderKey?: string, checkingSince?: number, snapshotRefused?: boolean, unanswered?: boolean, reviewSent?: ReviewSent } | null, * last: { fingerprint: string, versionId: string, exportedAt: string, projectId: string, files?: boolean, * snapshot?: ExportRequest["snapshot"], checksum?: string } - * | null }} VersionRecord */ + * | null, failure?: (Failure & { projectId: string }) | null }} VersionRecord */ /** `onAdded`: a version went ready, with whether it carries files and whether it is the page's first from here. * @typedef {{ onProgress?: (progress: ReviewExportProgress | null) => void, onUploaded?: () => Promise, @@ -193,12 +193,22 @@ function isLastMetadata(value) { } /** @param {Record} saved - * @returns {saved is {pending?: VersionRecord["pending"], last?: SavedLast | null}} */ + * @returns {saved is {pending?: VersionRecord["pending"], last?: SavedLast | null, failure?: unknown}} */ const isExportState = (saved) => ("pending" in saved || "last" in saved) && (saved.pending == null || isPending(saved.pending)) && (saved.last == null || isLast(saved.last)); +/** @param {unknown} value @returns {value is Failure & { projectId: string }} */ +const isSavedFailure = (value) => + isJsonObject(value) && + isSavedId(value.projectId) && + typeof value.exportKey === "string" && + typeof value.sentence === "string" && + typeof value.final === "boolean" && + typeof value.exportHelps === "boolean" && + isOptionalBoolean(value.held); + /** @param {string} dir @returns {Promise} */ async function readState(dir) { const file = statePath(dir); @@ -208,6 +218,7 @@ async function readState(dir) { const { last, pending } = saved; return { pending: pending ?? null, + failure: isSavedFailure(saved.failure) ? saved.failure : null, last: typeof last?.fingerprint === "string" ? { ...last, fingerprint: last.fingerprint } : null, }; } @@ -244,7 +255,7 @@ const failures = new Map(); /** Which export a failure was about: the newest export file and the project as it was rendered. @param {string} dir */ const exportKeyOf = (dir) => { const latest = latestExportFile(dir); - return latest ? `${latest.path}\n${latest.fingerprint ?? ""}` : ""; + return latest ? `${latest.path}\n${latest.fingerprint ?? ""}\n${latest.id}` : ""; }; /** Whether the newest export can go up now: there is one, it is MP4, and the project has not moved past it. @@ -269,7 +280,8 @@ export async function reviewVersion(projectPath, server = {}) { const last = state.last?.projectId === projectId ? state.last : null; const onServer = server.latestReadyVersionId === undefined || server.latestReadyVersionId === last?.versionId; - const failed = failures.get(key); + const savedFailure = state.failure?.projectId === projectId ? state.failure : null; + const failed = savedFailure ?? failures.get(key); return { last: last ? { exportedAt: last.exportedAt, current: last.fingerprint === now && onServer } @@ -590,18 +602,31 @@ const spent = (error, pending) => * @param {string} id @param {ExportDTO} done @param {FromReview | null} fromReview @returns {Promise} */ async function finish(dir, state, pending, id, done, fromReview) { const ready = done.status === "ready"; - const last = { - fingerprint: pending.body.source_fingerprint ?? "", - versionId: done.version_id, - exportedAt: done.exported_at, - projectId: id, - files: Boolean(pending.body.snapshot), - ...(pending.body.snapshot && { snapshot: pending.body.snapshot }), - checksum: pending.body.local_upload.checksum_sha256, - }; - await writeState(dir, { pending: null, last: ready ? last : state.last }); + const last = readyRecord(pending, id, done); + const failure = ready ? null : said(new ReviewFailed(200, done.error?.reason ?? "")); + await writeState(dir, { + pending: null, + last: ready ? last : state.last, + ...(failure && { + failure: { ...failure, projectId: id, exportKey: await failedExportKey(dir, pending) }, + }), + }); if (ready) await sharedFromReview(fromReview, dir, pending.reviewSent?.since); - return ready ? null : said(new ReviewFailed(200, done.error?.reason ?? "")); + return failure; +} + +/** @param {string} dir @param {NonNullable} pending */ +async function failedExportKey(dir, pending) { + if (typeof pending.renderKey === "string") return pending.renderKey; + const latest = latestExportFile(dir); + if (!latest) return ""; + const checksum = + latest.fingerprint === pending.body.source_fingerprint + ? await fileSha256Base64(latest.path).catch(() => null) + : null; + return checksum === pending.body.local_upload.checksum_sha256 + ? exportKeyOf(dir) + : `pending:${pending.body.client_operation_id}`; } /** @param {Required} r @param {(progress: ReviewExportProgress) => void} report @@ -638,7 +663,8 @@ function sameSourceMode(r, last, snapshot) { /** @param {ReviewClient} client @param {string} id @param {VersionRecord} state @param {ExportRequest} body */ async function alreadyUploaded(client, id, state, body) { const last = state.last; - if (state.pending || !last || last.projectId !== id) return false; + if (state.pending || state.failure?.projectId === id || !last || last.projectId !== id) + return false; if ( last.fingerprint !== body.source_fingerprint || last.checksum !== body.local_upload.checksum_sha256 @@ -650,10 +676,10 @@ async function alreadyUploaded(client, id, state, body) { * @param {{file: string, body: ExportRequest}} source @param {string} id @param {VersionRecord} state */ async function sendVersion(r, report, source, id, state) { const first = state.last?.projectId !== id; - let pending = bodyToSend(state, source.body, id); + let pending = bindRenderKey(bodyToSend(state, source.body, id), r.projectPath); const sourceConflict = pendingSourceConflict(r, pending, source.body); if (sourceConflict) return local(sourceConflict); - await writeState(r.projectPath, (state = { ...state, pending })); + await writeState(r.projectPath, (state = { ...state, pending, failure: null })); try { const answer = await createdExport(r, id, pending, (next) => writeState(r.projectPath, (state = { ...state, pending: next })), @@ -887,3 +913,23 @@ export async function pendingReviewExport(projectPath) { checksum: pending.body.local_upload.checksum_sha256, }; } + +/** @param {NonNullable} pending @param {string} id @param {ExportDTO} done */ +function readyRecord(pending, id, done) { + return { + fingerprint: pending.body.source_fingerprint ?? "", + versionId: done.version_id, + exportedAt: done.exported_at, + projectId: id, + files: Boolean(pending.body.snapshot), + ...(pending.body.snapshot && { snapshot: pending.body.snapshot }), + checksum: pending.body.local_upload.checksum_sha256, + }; +} + +/** @param {NonNullable} pending @param {string} dir */ +function bindRenderKey(pending, dir) { + return typeof pending.renderKey === "string" + ? pending + : { ...pending, renderKey: exportKeyOf(dir) }; +} diff --git a/packages/share/tests/reviewFailurePersistence.test.mjs b/packages/share/tests/reviewFailurePersistence.test.mjs new file mode 100644 index 0000000000..fefc79dbbf --- /dev/null +++ b/packages/share/tests/reviewFailurePersistence.test.mjs @@ -0,0 +1,196 @@ +import assert from "node:assert/strict"; +import { createHash } from "node:crypto"; +import { execFile } from "node:child_process"; +import { realpathSync } from "node:fs"; +import { mkdtemp, mkdir, writeFile, readFile, rm } from "node:fs/promises"; +import { tmpdir } from "node:os"; +import { join } from "node:path"; +import { promisify } from "node:util"; +import { test } from "node:test"; +import { addVersion, bindShareHost, refreshReviewExport } from "../src/index.mjs"; + +const run = promisify(execFile); +const moduleUrl = new URL("../src/index.mjs", import.meta.url).href; +async function fixture(t) { + const dir = realpathSync(await mkdtemp(join(tmpdir(), "hf-failed-export-"))); + t.after(() => rm(dir, { recursive: true, force: true })); + await mkdir(join(dir, ".hyperframes")); + await writeFile(join(dir, ".hyperframes", "video.mp4"), "video"); + await writeFile( + join(dir, ".hyperframes", "review.json"), + JSON.stringify({ + studioProjectId: "studio", + projectId: "project", + opened: true, + }), + ); + bindShareHost({ + normalize: realpathSync, + channelSite: "https://hyperframes.dev", + projectFingerprint: async () => "rendered", + latestExportFile: () => ({ + path: join(dir, ".hyperframes", "video.mp4"), + fingerprint: "rendered", + id: "render", + }), + }); + return dir; +} +async function readFromAnotherProcess(dir, fingerprint = "rendered", renderId = "render") { + const script = ` + import { realpathSync } from 'node:fs'; + import { join } from 'node:path'; + import { bindShareHost, reviewVersion } from ${JSON.stringify(moduleUrl)}; + const [dir, fingerprint, renderId] = process.argv.slice(1); + bindShareHost({ normalize: realpathSync, channelSite: 'https://hyperframes.dev', + projectFingerprint: async () => fingerprint, + latestExportFile: () => ({ path: join(dir, '.hyperframes', 'video.mp4'), fingerprint, id: renderId }), + }); + console.log(JSON.stringify(await reviewVersion(dir))); + `; + const { stdout } = await run(process.execPath, [ + "--input-type=module", + "-e", + script, + dir, + fingerprint, + renderId, + ]); + return JSON.parse(stdout); +} +const pending = { + projectId: "project", + videoId: "failed-video", + body: { + title_snapshot: "Video", + coordinate_width: 100, + coordinate_height: 100, + duration_seconds: 1, + render_settings: {}, + source_revision_id: null, + source_fingerprint: "rendered", + local_upload: { + checksum_sha256: createHash("sha256").update("video").digest("base64"), + content_type: "video/mp4", + size_bytes: 5, + }, + client_operation_id: "operation", + }, +}; +const ready = { + status: "ready", + video_id: "new-video", + version_id: "new-version", + exported_at: "2026-11-08T00:00:00Z", +}; +for (const update of [false, true]) { + test(`a rejected ${update ? "update" : "first export"} survives a new process until a successful retry`, async (t) => { + const dir = await fixture(t); + const file = join(dir, ".hyperframes", "review-export.json"); + const last = update + ? { + projectId: "project", + versionId: "old-version", + fingerprint: "old-render", + exportedAt: "2026-11-07T00:00:00Z", + } + : null; + await writeFile(file, JSON.stringify({ pending, last })); + await refreshReviewExport(dir, { + readExport: async () => ({ + status: "failed", + error: { reason: "content_rejected", message: "raw-sensitive-message" }, + }), + }); + const fresh = await readFromAnotherProcess(dir); + assert.equal(fresh.failure, "This video can't be shared."); + assert.equal(fresh.retryable, false); + assert.equal(fresh.last?.exportedAt ?? null, last?.exportedAt ?? null); + assert.equal((await readFromAnotherProcess(dir)).failure, fresh.failure); + assert.equal((await readFromAnotherProcess(dir, "new-render")).failure, null); + const saved = JSON.parse(await readFile(file, "utf8")); + assert.equal(saved.pending, null); + assert.equal(JSON.stringify(saved).includes("raw-sensitive-message"), false); + const error = await addVersion({ + projectPath: dir, + projectId: "project", + title: "Video", + probe: async () => ({ width: 100, height: 100, duration: 1 }), + client: { createExport: async () => ready }, + }); + assert.equal(error, null); + const succeeded = await readFromAnotherProcess(dir); + assert.equal(succeeded.failure, null); + assert.equal(succeeded.last.exportedAt, ready.exported_at); + }); +} + +test("malformed optional failure metadata is ignored and valid failures never follow another project", async (t) => { + const dir = await fixture(t); + const file = join(dir, ".hyperframes", "review-export.json"); + await writeFile(file, JSON.stringify({ pending, last: null })); + await refreshReviewExport(dir, { + readExport: async () => ({ status: "failed", error: { reason: "content_rejected" } }), + }); + await writeFile( + join(dir, ".hyperframes", "review.json"), + JSON.stringify({ + studioProjectId: "other-studio", + projectId: "other-project", + opened: true, + }), + ); + assert.equal((await readFromAnotherProcess(dir)).failure, null); + await writeFile( + file, + JSON.stringify({ pending: null, last: null, failure: { projectId: "other-project" } }), + ); + assert.equal((await readFromAnotherProcess(dir)).failure, null); +}); + +test("a replacement render with the same source cannot inherit the failed upload", async (t) => { + const dir = await fixture(t); + await addVersion({ + projectPath: dir, + projectId: "project", + title: "Video", + allowPending: true, + open: () => false, + probe: async () => ({ width: 100, height: 100, duration: 1 }), + client: { createExport: async () => ({ status: "processing", video_id: "video" }) }, + }); + await refreshReviewExport(dir, { + readExport: async () => ({ status: "failed", error: { reason: "content_rejected" } }), + }); + assert.equal((await readFromAnotherProcess(dir)).failure, "This video can't be shared."); + assert.equal((await readFromAnotherProcess(dir, "rendered", "new-render-id")).failure, null); +}); + +test("legacy pending uploads use the video checksum before binding a recovered failure", async (t) => { + const dir = await fixture(t); + await writeFile( + join(dir, ".hyperframes", "review-export.json"), + JSON.stringify({ pending, last: null }), + ); + await writeFile(join(dir, ".hyperframes", "video.mp4"), "replacement-video"); + await refreshReviewExport(dir, { + readExport: async () => ({ status: "failed", error: { reason: "content_rejected" } }), + }); + assert.equal((await readFromAnotherProcess(dir)).failure, null); +}); + +test("malformed optional failure leaves a valid pending upload and previous version intact", async (t) => { + const dir = await fixture(t); + const file = join(dir, ".hyperframes", "review-export.json"); + const last = { + projectId: "project", + versionId: "old", + fingerprint: "rendered", + exportedAt: "before", + }; + await writeFile(file, JSON.stringify({ pending, last, failure: { projectId: "project" } })); + const value = await readFromAnotherProcess(dir); + assert.equal(value.failure, null); + assert.equal(value.last.exportedAt, "before"); + assert.deepEqual(JSON.parse(await readFile(file, "utf8")).pending, pending); +}); diff --git a/packages/studio-server/src/index.ts b/packages/studio-server/src/index.ts index 0c309af4b8..3a0dd16b5c 100644 --- a/packages/studio-server/src/index.ts +++ b/packages/studio-server/src/index.ts @@ -78,3 +78,12 @@ export { createStudioMotionRenderBodyScript, type StudioMotionRenderScriptOptions, } from "./helpers/studioMotionRenderScript.js"; +export type { + LocalShareAudience, + LocalShareSpace, + LocalShareState, + LocalShareJob, + LocalShareSnapshot, + LocalShareAction, + LocalShareInteraction, +} from "./localShare.js"; diff --git a/packages/studio-server/src/localShare.ts b/packages/studio-server/src/localShare.ts new file mode 100644 index 0000000000..de3cf694c3 --- /dev/null +++ b/packages/studio-server/src/localShare.ts @@ -0,0 +1,45 @@ +export type LocalShareAudience = "public" | "team" | "invite" | "private"; +export interface LocalShareSpace { + id: string; + name: string; + bound: boolean; + canCreate: boolean; + plan?: "free" | "subscribed" | null; + upgradeUrl?: string | null; + audiences: LocalShareAudience[]; + used: number | null; + limit: number | null; +} +export interface LocalShareState { + state: "not_shared" | "link_off" | "ready" | "processing" | "failed" | "unavailable"; + url: string | null; + manageUrl: string; + changed: boolean | null; + hasReadyVersion?: boolean; + failure?: string | null; + audience: LocalShareAudience | null; + spaceId: string | null; + source: "not_checked" | "ready" | "video_only"; +} +export interface LocalShareJob { + id: string; + state: "running" | "done" | "failed"; + step: string; + result: LocalShareState | null; + error: { code: string; message: string } | null; +} +export interface LocalShareSnapshot { + versionSharing: boolean; + share: LocalShareState; + spaces: LocalShareSpace[]; + job: LocalShareJob | null; +} +export type LocalShareAction = { + action: "share" | "update" | "access" | "off" | "on" | "login"; + audience?: LocalShareAudience; + space?: string; + videoOnly?: boolean; +}; +export type LocalShareInteraction = + | { event: "share_opened"; link: "none" | "live" | "changed" } + | { event: "share_link_copied"; via: "copy" }; diff --git a/packages/studio/src/App.tsx b/packages/studio/src/App.tsx index e9b0ce971b..5071cfc083 100644 --- a/packages/studio/src/App.tsx +++ b/packages/studio/src/App.tsx @@ -517,6 +517,7 @@ export function StudioApp({ readOnlyPreview = false, readOnlyPreviewReason }: St inspectorButtonActive={inspectorButtonActive} inspectorPanelActive={inspectorPanelActive} onExport={handleExport} + beforeShare={previewPersistence.waitForPendingDomEditSaves} /> {previewPersistence.domEditSaveQueuePaused && !externalFileChanges.blocked && ( void; + beforeShare?: () => Promise; } /** @@ -45,6 +47,7 @@ export const StudioHeader = memo(function StudioHeader({ inspectorButtonActive, inspectorPanelActive, onExport, + beforeShare, }: StudioHeaderProps) { const showThemeToggle = useContext(ShowThemeToggle); const { projectId, renderQueue } = useStudioShellContext(); @@ -153,6 +156,7 @@ export const StudioHeader = memo(function StudioHeader({ {showThemeToggle && } + ; + +const interaction = vi.hoisted(() => vi.fn()); +vi.mock("./localShareTelemetry", () => ({ shareInteraction: interaction })); +vi.mock("../ui", () => ({ + Button: ({ children, variant: _variant, ...props }: ButtonProps) => ( + + ), + Menu: ({ children }: { children: React.ReactNode }) =>
{children}
, + MenuRadioGroup: ({ + children, + value, + onValueChange, + }: { + children: React.ReactNode; + value: string; + onValueChange: (value: string) => void; + }) => ( + + ), + MenuRadioItem: ({ value, disabled }: { value: string; disabled?: boolean }) => ( + + ), + Popover: ({ children }: { children: React.ReactNode }) =>
{children}
, +})); +const { QuickShare, QuickShareContent } = await import("./QuickShare"); +Reflect.set(globalThis, "IS_REACT_ACT_ENVIRONMENT", true); +let root: Root; +let host: HTMLDivElement; +let snapshot: LocalShareSnapshot; +let calls: unknown[]; +let job: LocalShareJob; +const token = "a".repeat(43); +beforeEach(() => { + interaction.mockReset(); + calls = []; + snapshot = { + versionSharing: true, + share: { + source: "not_checked", + state: "not_shared", + url: null, + manageUrl: "https://hyperframes.dev/shares", + changed: false, + audience: null, + spaceId: null, + }, + spaces: [ + { + id: "team1", + name: "Design team", + bound: true, + canCreate: true, + audiences: ["public", "private", "invite"], + used: 5, + limit: 5, + }, + ], + job: null, + }; + job = { id: "job1", state: "running", step: "uploading", result: null, error: null }; + host = document.createElement("div"); + document.body.append(host); + root = createRoot(host); + vi.stubGlobal( + "fetch", + vi.fn(async (url: string, init?: RequestInit) => { + expect(new Headers(init?.headers).get("X-Hyperframes-Share-CSRF")).toBe(token); + if (url.endsWith("/snapshot")) return Response.json(snapshot); + if (url.endsWith("/actions")) { + calls.push(JSON.parse(String(init?.body))); + return Response.json(job, { status: 202 }); + } + return Response.json(job); + }), + ); +}); +afterEach(() => { + act(() => root.unmount()); + host.remove(); + vi.unstubAllGlobals(); + vi.useRealTimers(); +}); +const button = (label: string) => + [...host.querySelectorAll("button")].find((element) => element.textContent === label); +async function mount(beforeShare?: () => Promise) { + await act(async () => root.render()); +} +async function choose(value: string) { + const select = host.querySelector('[aria-label="Who can access"]'); + if (!select) throw new Error("Missing audience"); + await act(async () => { + select.value = value; + select.dispatchEvent(new Event("change", { bubbles: true })); + }); +} +it("requires explicit audience, uses the bound workspace and permits server-authoritative quota retries", async () => { + await mount(); + expect(host.textContent).toContain("5 of 5 free share links used"); + expect(button("Create share link")?.disabled).toBe(true); + expect(calls).toEqual([]); + await choose("public"); + expect(button("Create share link")?.disabled).toBe(false); + await act(async () => button("Create share link")?.click()); + expect(calls).toEqual([{ action: "share", audience: "public", space: "team1" }]); +}); +it("drains pending editor saves before creating or uploading", async () => { + let resolveSave = () => {}; + const save = vi.fn( + () => + new Promise((resolve) => { + resolveSave = resolve; + }), + ); + await mount(save); + await choose("public"); + await act(async () => button("Create share link")?.click()); + expect(save).toHaveBeenCalledOnce(); + expect(calls).toEqual([]); + await act(async () => resolveSave()); + expect(calls).toHaveLength(1); +}); +it("does not publish when saving fails", async () => { + await mount(async () => { + throw new Error("write failed"); + }); + await choose("public"); + await act(async () => button("Create share link")?.click()); + expect(calls).toEqual([]); + expect(host.querySelector('[role="alert"]')).not.toBeNull(); +}); +it("shows stale copy separately and never uploads merely by opening", async () => { + snapshot.share = { + ...snapshot.share, + state: "ready", + url: "https://hyperframes.dev/r/live", + changed: true, + audience: "private", + spaceId: "team1", + }; + await mount(); + expect(button("Copy current shared link")).toBeDefined(); + expect(calls).toEqual([]); + await act(async () => button("Update shared version")?.click()); + expect(calls).toEqual([{ action: "update" }]); +}); +it("keeps link-off updates separate from explicit re-enabling", async () => { + snapshot.share = { ...snapshot.share, state: "link_off", audience: "private", spaceId: "team1" }; + await mount(); + expect(button("Turn link on")).toBeDefined(); + await act(async () => button("Update shared version")?.click()); + expect(calls).toEqual([{ action: "update" }]); +}); +it("recovers a running job on reopening, and stops browser polling on close", async () => { + vi.useFakeTimers(); + snapshot.job = job; + await mount(); + expect(host.textContent).toContain("Uploading your video"); + expect(calls).toEqual([]); + await act(async () => root.render(null)); + const before = vi.mocked(fetch).mock.calls.length; + await act(async () => vi.advanceTimersByTime(3000)); + expect(vi.mocked(fetch).mock.calls.length).toBe(before); + await mount(); + expect(host.textContent).toContain("Uploading your video"); + expect(calls).toEqual([]); +}); +it("hides creation while feature is off but keeps existing management", async () => { + snapshot.versionSharing = false; + snapshot.share = { ...snapshot.share, state: "link_off", audience: "private", spaceId: "team1" }; + await mount(); + expect(button("Update shared version")).toBeUndefined(); + expect(button("Turn link on")).toBeDefined(); +}); +it("recovers a failed job on reopening instead of silently dropping the error", async () => { + snapshot.job = { + ...job, + state: "failed", + error: { code: "share_failed", message: "The upload failed. Try again." }, + }; + await mount(); + expect(host.querySelector('[role="alert"]')?.textContent).toContain("The upload failed"); + expect(calls).toEqual([]); +}); + +it("offers video-only recovery explicitly after a failed source upload", async () => { + snapshot.share = { + ...snapshot.share, + state: "processing", + audience: "private", + spaceId: "team1", + }; + snapshot.job = { + ...job, + state: "failed", + error: { code: "source_unavailable", message: "Project files could not be attached." }, + }; + await mount(); + expect(calls).toEqual([]); + await act(async () => button("Retry with video only")?.click()); + expect(calls).toEqual([{ action: "update", videoOnly: true }]); +}); +it("labels files as included only after a ready upload result", async () => { + snapshot.job = { + ...job, + state: "done", + result: { ...snapshot.share, state: "ready", source: "ready" }, + }; + await mount(); + expect(host.textContent).toContain("Last Studio upload: project files included."); +}); +it.each(["unauthenticated", "login_expired"])( + "offers explicit browser login for %s and recovers signed-out polling", + async (code) => { + vi.stubGlobal( + "fetch", + vi.fn(async (url: string, init?: RequestInit) => { + if (url.endsWith("/actions")) { + calls.push(JSON.parse(String(init?.body))); + return Response.json({ ...job, step: "signing_in" }); + } + return Response.json({ code, message: "Sign in to share.", job: null }, { status: 400 }); + }), + ); + await mount(); + expect(calls).toEqual([]); + expect(button("Sign in")).toBeDefined(); + await act(async () => button("Sign in")?.click()); + expect(calls).toEqual([{ action: "login" }]); + expect(host.textContent).toContain("Finish signing in in your browser"); + }, +); + +it("records a copy only after the clipboard succeeds and opening once per panel", async () => { + snapshot.share = { + ...snapshot.share, + state: "ready", + url: "https://hyperframes.dev/r/old", + audience: "private", + spaceId: "team1", + }; + const copy = vi.spyOn(navigator.clipboard, "writeText"); + copy.mockRejectedValueOnce(new Error("denied")).mockResolvedValue(undefined); + await mount(); + expect(interaction).toHaveBeenCalledExactlyOnceWith(token, { + event: "share_opened", + link: "live", + }); + await act(async () => button("Copy link")?.click()); + expect(interaction).toHaveBeenCalledTimes(1); + await act(async () => button("Copy link")?.click()); + expect(interaction).toHaveBeenLastCalledWith(token, { event: "share_link_copied", via: "copy" }); + expect(calls).toEqual([]); + copy.mockRestore(); +}); + +it("clears account-specific links and workspace controls after an identity failure", async () => { + snapshot.share = { + ...snapshot.share, + state: "ready", + url: "https://hyperframes.dev/r/private", + audience: "private", + spaceId: "team1", + }; + await mount(); + expect(button("Copy link")).toBeDefined(); + vi.mocked(fetch).mockResolvedValue( + Response.json({ code: "login_changed", message: "Your login changed" }, { status: 400 }), + ); + await act(async () => button("Update shared version")?.click()); + expect(button("Copy link")).toBeUndefined(); + expect(button("Update shared version")).toBeUndefined(); + expect(host.querySelector('[aria-label="Sharing workspace"]')).toBeNull(); + expect(host.textContent).not.toContain("Design team"); + expect(button("Sign in")).toBeDefined(); +}); + +it("does not claim an older upload is current when its portable content identity is unknown", async () => { + snapshot.share = { + ...snapshot.share, + state: "ready", + changed: null, + url: "https://hyperframes.dev/r/live", + }; + await mount(); + expect(button("Copy current shared link")).toBeDefined(); + expect(host.textContent).toContain("Changes after your last upload aren’t shared automatically"); +}); + +it("continues from a running browser login to fresh controls without refreshing or publishing", async () => { + vi.useFakeTimers(); + let signedIn = false; + const loginJob = { ...job, step: "signing_in" }; + vi.mocked(fetch).mockImplementation(async (url, init) => { + const path = String(url); + if (path.endsWith("/actions")) { + calls.push(JSON.parse(String(init?.body))); + return Response.json(loginJob, { status: 202 }); + } + if (path.includes("/jobs/")) + return Response.json( + signedIn ? { ...loginJob, state: "done", result: snapshot.share } : loginJob, + ); + return signedIn + ? Response.json({ ...snapshot, job: { ...loginJob, state: "done", result: snapshot.share } }) + : Response.json({ code: "login_expired", message: "Sign in again." }, { status: 400 }); + }); + await mount(); + await act(async () => button("Sign in")?.click()); + await act(async () => vi.advanceTimersByTime(1000)); + expect(host.textContent).toContain("Finish signing in"); + signedIn = true; + await act(async () => vi.advanceTimersByTime(1000)); + expect(button("Sign in")).toBeUndefined(); + expect(host.querySelector('[aria-label="Who can access"]')).not.toBeNull(); + expect(button("Create share link")?.disabled).toBe(true); + expect(calls).toEqual([{ action: "login" }]); +}); + +it.each(["snapshot", "poll"])( + "reconnects on return after a %s error without a refresh press", + async (failureAt) => { + vi.useFakeTimers(); + let restored = false; + snapshot.job = failureAt === "poll" ? { ...job, step: "signing_in" } : null; + vi.mocked(fetch).mockImplementation(async (url) => { + if (restored) return Response.json({ ...snapshot, job: null }); + if (failureAt === "snapshot") + return Response.json({ code: "login_expired", message: "Sign in again." }, { status: 400 }); + if (String(url).includes("/jobs/")) throw new Error("Connection lost"); + return Response.json(snapshot); + }); + await mount(); + if (failureAt === "poll") await act(async () => vi.advanceTimersByTime(1000)); + restored = true; + await act(async () => window.dispatchEvent(new Event("focus"))); + expect(host.querySelector('[aria-label="Who can access"]')).not.toBeNull(); + expect(button("Create share link")?.disabled).toBe(true); + expect(calls).toEqual([]); + }, +); + +it("keeps audience choices when a healthy panel regains focus", async () => { + await mount(); + await choose("invite"); + const requests = vi.mocked(fetch).mock.calls.length; + await act(async () => window.dispatchEvent(new Event("focus"))); + await act(async () => document.dispatchEvent(new Event("visibilitychange"))); + expect(host.querySelector('[aria-label="Who can access"]')?.value).toBe( + "invite", + ); + expect(vi.mocked(fetch).mock.calls.length).toBe(requests); + expect(calls).toEqual([]); +}); + +it("does not send an authenticated sharing-admission refusal into another login loop", async () => { + vi.mocked(fetch).mockResolvedValue( + Response.json( + { + code: "sharing_not_admitted", + message: + "You're signed in, but sharing isn't accepting this sign-in. Try again later or contact support.", + }, + { status: 400 }, + ), + ); + await mount(); + expect(host.textContent).toContain("You're signed in"); + expect(button("Sign in")).toBeUndefined(); + expect(button("Create share link")).toBeUndefined(); + expect(calls).toEqual([]); +}); + +it("shows retry only for recoverable errors, never a permanent refresh footer", async () => { + await mount(); + expect(button("Refresh")).toBeUndefined(); + expect(button("Try again")).toBeUndefined(); +}); + +it.each(["login_expired", "sharing_not_admitted", "review_upload_origins_required"])( + "does not offer a misleading retry for %s", + async (code) => { + vi.mocked(fetch).mockResolvedValue( + Response.json({ code, message: "Unavailable" }, { status: 400 }), + ); + await mount(); + expect(button("Try again")).toBeUndefined(); + }, +); + +it.each(["request", "job"])( + "restores the create action and audience after a failed %s", + async (failureAt) => { + await mount(); + await choose("public"); + const failed = { + ...job, + state: "failed" as const, + error: { code: "share_failed", message: "Cannot render" }, + }; + if (failureAt === "request") + vi.mocked(fetch).mockResolvedValueOnce(Response.json(failed.error, { status: 400 })); + else { + job = failed; + snapshot.job = failed; + } + await act(async () => button("Create share link")?.click()); + expect(button("Create share link")?.disabled).toBe(false); + expect(host.querySelector('[aria-label="Who can access"]')?.value).toBe( + "public", + ); + expect(button("Try again")).toBeUndefined(); + expect(host.textContent).toContain("Cannot render"); + }, +); + +it("uses the OAuth-selected workspace among several without a dropdown", async () => { + snapshot.spaces.unshift({ ...snapshot.spaces[0]!, id: "other", name: "Other", bound: false }); + await mount(); + expect(host.querySelector('[aria-label="Sharing workspace"]')).toBeNull(); + await choose("public"); + await act(async () => button("Create share link")?.click()); + expect(calls).toEqual([{ action: "share", audience: "public", space: "team1" }]); +}); +it("refuses to substitute another workspace when the OAuth selection is missing", async () => { + snapshot.spaces[0]!.bound = false; + await mount(); + expect(button("Create share link")?.disabled).toBe(true); + expect(host.textContent).toContain("workspace selected at sign-in"); + expect(calls).toEqual([]); +}); + +it("omits Only you for new shares but preserves an existing private audience", async () => { + await mount(); + expect(host.querySelector('option[value="private"]')).toBeNull(); +}); +it("displays an existing private share without converting its audience", async () => { + snapshot.share = { ...snapshot.share, state: "ready", audience: "private", spaceId: "team1" }; + await mount(); + expect(host.querySelector('[aria-label="Who can access"]')?.value).toBe( + "private", + ); + expect(host.textContent).toContain("Only you"); + expect(calls).toEqual([]); +}); + +it("resumes a failed first creation without presenting an uploaded version", async () => { + snapshot.share = { + ...snapshot.share, + state: "processing", + audience: "public", + spaceId: "team1", + hasReadyVersion: false, + }; + snapshot.job = { + ...job, + state: "failed", + error: { code: "source_unavailable", message: "Project files could not upload" }, + }; + await mount(); + expect(button("Create share link")?.disabled).toBe(false); + expect(button("Update shared version")).toBeUndefined(); + expect(host.textContent).not.toContain("still being prepared"); + await act(async () => button("Create share link")?.click()); + expect(calls).toEqual([{ action: "update" }]); +}); + +it.each(["free", "subscribed", null] as const)( + "shows the Pro CTA only for authoritative free entitlement: %s", + async (plan) => { + snapshot.spaces[0]!.plan = plan; + snapshot.spaces[0]!.upgradeUrl = "https://hyperframes.dev/pricing"; + await mount(); + const link = [...host.querySelectorAll("a")].find((a) => + a.textContent?.includes("Upgrade to Pro"), + ); + if (plan === "free") expect(link?.href).toBe("https://hyperframes.dev/pricing"); + else expect(link).toBeUndefined(); + }, +); +it("refuses an upgrade destination outside the public pricing flow", async () => { + snapshot.spaces[0]!.plan = "free"; + snapshot.spaces[0]!.upgradeUrl = "https://example.com/checkout"; + await mount(); + expect(host.textContent).not.toContain("Upgrade to Pro"); +}); + +it.each([false, true])( + "shows a persisted failed export after reopen (previous version: %s)", + async (previous) => { + snapshot.share = { + ...snapshot.share, + state: "failed", + failure: "This video can't be shared.", + hasReadyVersion: previous, + changed: true, + audience: "public", + spaceId: "team1", + url: previous ? "https://hyperframes.dev/r/previous" : null, + }; + await mount(); + expect(host.querySelector('[role="alert"]')?.textContent).toBe("This video can't be shared."); + expect(host.textContent).not.toContain("still being prepared"); + expect(calls).toEqual([]); + const action = button(previous ? "Update shared version" : "Create share link"); + expect(action?.disabled).toBe(false); + if (previous) expect(button("Copy current shared link")).toBeDefined(); + await act(async () => action?.click()); + expect(calls).toEqual([{ action: "update" }]); + }, +); + +it("does not probe unsupported Studio hosts for the CLI sharing bridge", async () => { + await act(async () => root.render()); + expect(fetch).not.toHaveBeenCalled(); +}); + +it("bootstraps sharing when the CLI advertises its bridge", async () => { + const marker = document.createElement("meta"); + marker.name = "hyperframes-local-share"; + marker.content = "1"; + document.head.append(marker); + vi.mocked(fetch).mockResolvedValue(Response.json({ csrf: token })); + try { + await act(async () => root.render()); + expect(fetch).toHaveBeenCalledWith( + "/api/share/bootstrap", + expect.objectContaining({ method: "GET" }), + ); + } finally { + marker.remove(); + } +}); diff --git a/packages/studio/src/components/share/QuickShare.tsx b/packages/studio/src/components/share/QuickShare.tsx new file mode 100644 index 0000000000..a3a26a0f5f --- /dev/null +++ b/packages/studio/src/components/share/QuickShare.tsx @@ -0,0 +1,102 @@ +import { useState } from "react"; +import { useMountEffect } from "../../hooks/useMountEffect"; +import { Button, Popover } from "../ui"; +import { shareBootstrap, safeShareUrl } from "./localShareClient"; +import { useQuickShare } from "./useQuickShare"; +import { + ShareSettings, + ShareNotices, + ShareActions, + ShareSourceStatus, + ShareLogin, + SharePlan, +} from "./QuickShareControls"; +export function QuickShare({ beforeShare }: { beforeShare?: () => Promise }) { + const [token, setToken] = useState(null); + const [open, setOpen] = useState(false); + useMountEffect(() => { + if (!document.querySelector('meta[name="hyperframes-local-share"][content="1"]')) return; + const controller = new AbortController(); + void shareBootstrap(controller.signal) + .then((value) => { + if (!controller.signal.aborted) setToken(value); + }) + .catch(() => {}); + return () => controller.abort(); + }); + if (!token) return null; + return ( + Share} + className="w-96 max-w-[calc(100vw-2rem)] rounded-2xl p-4" + > + {open ? : null} + + ); +} + +export function QuickShareContent({ + token, + beforeShare, +}: { + token: string; + beforeShare?: () => Promise; +}) { + const model = useQuickShare(token, beforeShare); + const { snapshot, progress, error } = model; + const url = safeShareUrl(snapshot?.share.url ?? ""); + const manageUrl = safeShareUrl(snapshot?.share.manageUrl ?? ""); + return ( +
+
+

Share project

+

Share the latest saved project.

+
+ {snapshot ? ( + <> + + + + + + + ) : null} + {!snapshot && !error ?

Loading sharing…

: null} + {progress ? ( +

{progress} You can close this panel; keep Studio running.

+ ) : null} + + {error ? ( +

+ {error} +

+ ) : null} +
+ {manageUrl ? ( + + Manage sharing + + ) : null} + {url ? ( + + Open shared page + + ) : null} +
+
+ ); +} diff --git a/packages/studio/src/components/share/QuickShareControls.tsx b/packages/studio/src/components/share/QuickShareControls.tsx new file mode 100644 index 0000000000..bb1603707b --- /dev/null +++ b/packages/studio/src/components/share/QuickShareControls.tsx @@ -0,0 +1,243 @@ +import type { LocalShareSnapshot } from "@hyperframes/studio-server"; +import { Button } from "../ui"; +import { ShareAudience } from "./ShareAudience"; +import { Link, ArrowUpRight } from "@phosphor-icons/react"; +import type { QuickShareModel } from "./useQuickShare"; + +type Props = { model: QuickShareModel; snapshot: LocalShareSnapshot }; +export function ShareSettings({ model, snapshot }: Props) { + return ; +} +export function ShareNotices({ model, snapshot }: Props) { + const { share } = snapshot; + const messages = [ + model.audience === "invite" ? "Add people from Manage sharing after creating the link." : null, + share.changed + ? "Local changes aren’t shared yet. Update the shared version when you’re ready." + : share.changed === null + ? "Changes after your last upload aren’t shared automatically. Update to share the current project." + : null, + share.state === "link_off" ? "The link is off. Updating the video keeps it off." : null, + share.state === "processing" && !model.busy && snapshot.job?.state !== "failed" + ? "The shared video is still being prepared. Reopen sharing to check its status." + : null, + share.state === "unavailable" ? "Sharing is paused. Open Manage sharing for details." : null, + !snapshot.versionSharing && share.state === "not_shared" + ? "Sharing isn’t available for this account yet." + : null, + ]; + return ( + <> + {share.state === "failed" && share.failure ? ( +

+ {share.failure} +

+ ) : null} + {messages.filter(Boolean).map((message) => ( +

+ {message} +

+ ))} + + ); +} +export function ShareActions({ model, snapshot, url }: Props & { url: string | null }) { + if (snapshot.share.state === "not_shared") + return ; + return ( + <> + {url ? : null} + {snapshot.versionSharing && snapshot.share.state !== "unavailable" ? ( + + ) : null} + + + ); +} +function CreateShare({ model, snapshot }: Props) { + const space = snapshot.spaces.find((item) => item.id === model.spaceId); + const canCreate = snapshot.versionSharing && space?.canCreate && model.audience !== ""; + return ( + <> + {!space || !space.canCreate ? ( +

+ Sharing isn’t available in the workspace selected at sign-in. Sign in with an accessible + workspace to continue. +

+ ) : null} + + + ); +} +function CopyShare({ model, snapshot, url }: Props & { url: string }) { + const label = model.copied + ? "Copied" + : snapshot.share.changed !== false + ? "Copy current shared link" + : "Copy link"; + return ( +
+ + {url.replace(/^https:\/\//, "")} + + +
+ ); +} +function ManageShare({ model, snapshot, url }: Props & { url: string | null }) { + return ( +
+ {model.audience && model.audience !== snapshot.share.audience ? ( + + ) : null} + {snapshot.share.state === "link_off" ? ( + + ) : null} + {url ? ( + + ) : null} +
+ ); +} + +export function ShareSourceStatus({ model, snapshot }: Props) { + const last = snapshot.job?.result; + const recover = snapshot.job?.error?.code === "source_unavailable"; + let message = "Project files are checked when you share."; + if (last?.source === "video_only") + message = "Last Studio upload: video only. Project files weren’t included."; + if (last?.source === "ready") + message = + last.state === "ready" + ? "Last Studio upload: project files included." + : "Project files are ready; sharing is still processing."; + return ( + <> +

{message}

+ {recover ? ( + + ) : null} + + ); +} + +export function ShareLogin({ model }: { model: QuickShareModel }) { + if ( + !model.errorCode || + ![ + "not_configured", + "unauthenticated", + "login_expired", + "login_changed", + "refresh_failed", + "device_auth_failed", + ].includes(model.errorCode) + ) + return null; + return ( + <> + +

+ Or run hyperframes auth login in your terminal, then return to Studio. Sharing + reconnects automatically. +

+ + ); +} + +export function SharePlan({ model, snapshot }: Props) { + const space = snapshot.spaces.find((item) => item.id === model.spaceId); + const upgrade = space?.upgradeUrl; + const allowed = + upgrade && + ["https://hyperframes.dev/pricing", "https://dev.hyperframes.dev/pricing"].includes(upgrade); + return ( +
+ {space && space.limit !== null && space.used !== null ? ( + + {space.used} of {space.limit} free share links used + + ) : null} + {space?.plan === "free" && allowed ? ( + + Upgrade to Pro + + ) : null} +
+ ); +} diff --git a/packages/studio/src/components/share/ShareAudience.tsx b/packages/studio/src/components/share/ShareAudience.tsx new file mode 100644 index 0000000000..46d9667e81 --- /dev/null +++ b/packages/studio/src/components/share/ShareAudience.tsx @@ -0,0 +1,92 @@ +import { CaretDown, Globe, Lock, Users, UserPlus } from "@phosphor-icons/react"; +import type { LocalShareAudience, LocalShareSnapshot } from "@hyperframes/studio-server"; +import { Menu, MenuRadioGroup, MenuRadioItem } from "../ui"; +import { isAudience } from "./localShareClient"; +import type { QuickShareModel } from "./useQuickShare"; + +const AUDIENCES = { + public: { label: "Anyone with the link", detail: "Anyone you send the link to", icon: Globe }, + team: { + label: "Anyone in this workspace", + detail: "People in your signed-in workspace", + icon: Users, + }, + invite: { + label: "Only invited people", + detail: "People you add in Manage sharing", + icon: UserPlus, + }, + private: { label: "Only you", detail: "This existing share is private", icon: Lock }, +}; + +export function ShareAudience({ + model, + snapshot, +}: { + model: QuickShareModel; + snapshot: LocalShareSnapshot; +}) { + const selected = model.audience ? AUDIENCES[model.audience] : null; + const Icon = selected?.icon ?? Lock; + const space = snapshot.spaces.find((item) => item.id === model.spaceId); + const choices: LocalShareAudience[] = ["public", "team", "invite"]; + if (snapshot.share.audience === "private") choices.push("private"); + return ( + + + + + {selected?.label ?? "Choose who can access"} + + + ); +} diff --git a/packages/studio/src/components/share/localShareClient.ts b/packages/studio/src/components/share/localShareClient.ts new file mode 100644 index 0000000000..c2002fdc0e --- /dev/null +++ b/packages/studio/src/components/share/localShareClient.ts @@ -0,0 +1,171 @@ +import type { + LocalShareAction, + LocalShareAudience, + LocalShareJob, + LocalShareSnapshot, + LocalShareState, + LocalShareSpace, +} from "@hyperframes/studio-server"; +import { studioApiFetch } from "../../utils/studioApiFetch"; + +const audiences: readonly LocalShareAudience[] = ["public", "team", "invite", "private"]; +const record = (value: unknown): value is Record => + typeof value === "object" && value !== null && !Array.isArray(value); +const text = (value: unknown): value is string => typeof value === "string"; +const nullableText = (value: unknown): value is string | null => value === null || text(value); +const nullableBoolean = (value: unknown): value is boolean | null => + value === null || typeof value === "boolean"; +const nullableNumber = (value: unknown): value is number | null => + value === null || (typeof value === "number" && Number.isFinite(value)); +export const isAudience = (value: unknown): value is LocalShareAudience => + audiences.some((mode) => mode === value); +function isState(value: unknown): value is LocalShareState { + return ( + record(value) && + ["not_shared", "link_off", "ready", "processing", "failed", "unavailable"].includes( + String(value.state), + ) && + optionalFailure(value.failure) && + nullableText(value.url) && + text(value.manageUrl) && + nullableBoolean(value.changed) && + nullableAudience(value.audience) && + nullableText(value.spaceId) && + ["not_checked", "ready", "video_only"].includes(String(value.source)) + ); +} +function isSpace(value: unknown): value is LocalShareSpace { + return ( + record(value) && + text(value.id) && + text(value.name) && + typeof value.bound === "boolean" && + typeof value.canCreate === "boolean" && + Array.isArray(value.audiences) && + value.audiences.every(isAudience) && + nullableNumber(value.used) && + nullableNumber(value.limit) + ); +} +function isError(value: unknown): boolean { + return value === null || (record(value) && text(value.code) && text(value.message)); +} + +function isJob(value: unknown): value is LocalShareJob { + return ( + record(value) && + text(value.id) && + ["running", "done", "failed"].includes(String(value.state)) && + text(value.step) && + (value.result === null || isState(value.result)) && + isError(value.error) + ); +} +function isSnapshot(value: unknown): value is LocalShareSnapshot { + return ( + record(value) && + typeof value.versionSharing === "boolean" && + isState(value.share) && + Array.isArray(value.spaces) && + value.spaces.every(isSpace) && + (value.job === null || isJob(value.job)) + ); +} +export class LocalShareError extends Error { + constructor( + public readonly code: string, + message: string, + public readonly job: LocalShareJob | null = null, + ) { + super(message); + } +} +async function json( + path: string, + token: string | null, + signal: AbortSignal, + action?: LocalShareAction, +): Promise { + const response = await studioApiFetch(`/api/share/${path}`, { + method: action ? "POST" : "GET", + signal: AbortSignal.any([signal, AbortSignal.timeout(30_000)]), + headers: { + ...(token ? { "X-Hyperframes-Share-CSRF": token } : {}), + ...(action ? { "Content-Type": "application/json" } : {}), + }, + ...(action ? { body: JSON.stringify(action) } : {}), + }); + const body: unknown = await response.json().catch(() => null); + if (!response.ok) throw responseError(body); + return body; +} +function responseError(body: unknown): LocalShareError { + const code = record(body) && text(body.code) ? body.code : "unavailable"; + const message = + record(body) && text(body.message) + ? body.message + : "Sharing is unavailable. Try again from a local Studio preview."; + const job = record(body) && isJob(body.job) ? body.job : null; + return new LocalShareError(code, message, job); +} + +export async function shareBootstrap(signal: AbortSignal): Promise { + const value = await json("bootstrap", null, signal); + if (!record(value) || !text(value.csrf) || !/^[A-Za-z0-9_-]{43}$/.test(value.csrf)) + throw new LocalShareError("unavailable", "Sharing is not available in this Studio host."); + return value.csrf; +} +export async function shareSnapshot( + token: string, + signal: AbortSignal, +): Promise { + const value = await json("snapshot", token, signal); + if (!isSnapshot(value)) + throw new LocalShareError( + "unavailable", + "Sharing returned an unreadable response. Refresh Studio.", + ); + return value; +} +export async function shareAction( + token: string, + action: LocalShareAction, + signal: AbortSignal, +): Promise { + const value = await json("actions", token, signal, action); + if (!isJob(value)) + throw new LocalShareError( + "unavailable", + "Could not start sharing. Refresh to check its status.", + ); + return value; +} +export async function shareJob( + token: string, + id: string, + signal: AbortSignal, +): Promise { + const value = await json(`jobs/${encodeURIComponent(id)}`, token, signal); + if (!isJob(value)) + throw new LocalShareError( + "unavailable", + "Could not read sharing progress. Refresh to check its status.", + ); + return value; +} +export function safeShareUrl(value: string): string | null { + try { + const url = new URL(value); + return url.protocol === "https:" && !url.username && !url.password ? url.href : null; + } catch { + return null; + } +} + +function optionalFailure(value: unknown): boolean { + return value === undefined || nullableText(value); +} + +function nullableAudience(value: unknown): boolean { + return value === null || isAudience(value); +} diff --git a/packages/studio/src/components/share/localShareTelemetry.test.ts b/packages/studio/src/components/share/localShareTelemetry.test.ts new file mode 100644 index 0000000000..b98659de7a --- /dev/null +++ b/packages/studio/src/components/share/localShareTelemetry.test.ts @@ -0,0 +1,22 @@ +import { afterEach, expect, it, vi } from "vitest"; +const policy = vi.hoisted(() => vi.fn()); +vi.mock("../../telemetry/policy", () => ({ browserTelemetryAllowed: policy })); +import { shareInteraction } from "./localShareTelemetry"; +afterEach(() => vi.unstubAllGlobals()); +it("obeys browser opt-out before calling the guarded local bridge", async () => { + const fetch = vi.fn(async () => new Response(null, { status: 204 })); + vi.stubGlobal("fetch", fetch); + policy.mockReturnValue(false); + shareInteraction("token", { event: "share_opened", link: "none" }); + expect(fetch).not.toHaveBeenCalled(); + policy.mockReturnValue(true); + shareInteraction("token", { event: "share_link_copied", via: "copy" }); + expect(fetch).toHaveBeenCalledWith( + "/api/share/events", + expect.objectContaining({ + method: "POST", + headers: { "Content-Type": "application/json", "X-Hyperframes-Share-CSRF": "token" }, + body: JSON.stringify({ event: "share_link_copied", via: "copy" }), + }), + ); +}); diff --git a/packages/studio/src/components/share/localShareTelemetry.ts b/packages/studio/src/components/share/localShareTelemetry.ts new file mode 100644 index 0000000000..965b2ca8bb --- /dev/null +++ b/packages/studio/src/components/share/localShareTelemetry.ts @@ -0,0 +1,13 @@ +import type { LocalShareInteraction } from "@hyperframes/studio-server"; +import { browserTelemetryAllowed } from "../../telemetry/policy"; +import { studioApiFetch } from "../../utils/studioApiFetch"; + +export function shareInteraction(token: string, event: LocalShareInteraction): void { + if (!browserTelemetryAllowed()) return; + void studioApiFetch("/api/share/events", { + method: "POST", + signal: AbortSignal.timeout(5000), + headers: { "Content-Type": "application/json", "X-Hyperframes-Share-CSRF": token }, + body: JSON.stringify(event), + }).catch(() => {}); +} diff --git a/packages/studio/src/components/share/useQuickShare.ts b/packages/studio/src/components/share/useQuickShare.ts new file mode 100644 index 0000000000..0015be0144 --- /dev/null +++ b/packages/studio/src/components/share/useQuickShare.ts @@ -0,0 +1,189 @@ +import { useRef, useState } from "react"; +import type { + LocalShareAction, + LocalShareAudience, + LocalShareJob, + LocalShareSnapshot, +} from "@hyperframes/studio-server"; +import { useMountEffect } from "../../hooks/useMountEffect"; +import { LocalShareError, shareAction, shareJob, shareSnapshot } from "./localShareClient"; +import { shareInteraction } from "./localShareTelemetry"; +const STEP_LABELS: Record = { + preparing: "Preparing your video…", + signing_in: "Finish signing in in your browser…", + uploading: "Uploading your video…", + processing: "Processing your video…", + checking: "Checking your video…", +}; +const failure = (error: unknown) => + error instanceof LocalShareError + ? error.message + : "Sharing couldn’t finish. Try again to check its status."; + +export function useQuickShare(token: string, beforeShare?: () => Promise) { + const [snapshot, setSnapshot] = useState(null); + const [audience, setAudience] = useState(""); + const [spaceId, setSpaceId] = useState(""); + const [busy, setBusyState] = useState(false); + const working = useRef(false); + const reconnectOnReturn = useRef(false); + const [error, setError] = useState(null); + const [errorCode, setErrorCode] = useState(null); + const [copied, setCopied] = useState(false); + const opened = useRef(false); + const lifetime = useRef(null); + const timer = useRef | null>(null); + const [progress, setProgress] = useState(""); + + function setWorking(value: boolean) { + working.current = value; + setBusyState(value); + } + + async function poll(job: LocalShareJob, signal: AbortSignal) { + if (signal.aborted) return; + if (job.state === "running") { + setWorking(true); + setProgress(STEP_LABELS[job.step] ?? "Preparing share…"); + timer.current = setTimeout(() => { + void shareJob(token, job.id, signal) + .then((next) => poll(next, signal)) + .catch((cause) => { + reportFailure(cause, signal); + }); + }, 1000); + return; + } + setWorking(false); + setProgress(""); + const result = job.result; + if (result) setSnapshot((prior) => (prior ? { ...prior, share: result, job } : prior)); + await refresh(signal, job.state === "failed"); + } + async function refresh(signal: AbortSignal, preserveSelection = false) { + setError(null); + setErrorCode(null); + setWorking(true); + if (timer.current) clearTimeout(timer.current); + try { + const next = await shareSnapshot(token, signal); + if (signal.aborted) return; + recordOpen(next); + reconnectOnReturn.current = false; + setSnapshot(next); + if (!preserveSelection) resetSelection(next); + if (next.job?.error) { + setError(next.job.error.message); + setErrorCode(next.job.error.code); + } + if (next.job?.state === "running") await poll(next.job, signal); + else setWorking(false); + return true; + } catch (cause) { + reportFailure(cause, signal); + return false; + } + } + useMountEffect(() => { + const controller = new AbortController(); + lifetime.current = controller; + const resume = () => { + if (document.visibilityState !== "hidden" && reconnectOnReturn.current && !working.current) + void refresh(controller.signal); + }; + window.addEventListener("focus", resume); + document.addEventListener("visibilitychange", resume); + void refresh(controller.signal); + return () => { + window.removeEventListener("focus", resume); + document.removeEventListener("visibilitychange", resume); + controller.abort(); + if (timer.current) clearTimeout(timer.current); + }; + }); + async function run(action: LocalShareAction) { + const signal = lifetime.current?.signal; + if (!signal || signal.aborted || working.current) return; + setWorking(true); + setError(null); + setErrorCode(null); + setCopied(false); + setProgress("Preparing share…"); + try { + if (["share", "update"].includes(action.action)) await beforeShare?.(); + if (!signal.aborted) await poll(await shareAction(token, action, signal), signal); + } catch (cause) { + await recoverActionFailure(cause, signal); + } + } + async function recoverActionFailure(cause: unknown, signal: AbortSignal) { + if ( + cause instanceof LocalShareError && + [ + "login_changed", + "login_expired", + "unauthenticated", + "refresh_failed", + "not_configured", + ].includes(cause.code) + ) { + reportFailure(cause, signal); + return; + } + setProgress(""); + const recovered = await refresh(signal, true); + if (recovered && !signal.aborted) { + setError(failure(cause)); + setErrorCode(cause instanceof LocalShareError ? cause.code : null); + } + } + function recordOpen(value: LocalShareSnapshot | null) { + if (opened.current) return; + opened.current = true; + const share = value?.share; + const link = share?.url ? (share.changed ? "changed" : "live") : "none"; + shareInteraction(token, { event: "share_opened", link }); + } + function resetSelection(next: LocalShareSnapshot) { + setAudience(next.share.audience ?? ""); + setSpaceId(next.share.spaceId ?? next.spaces.find((space) => space.bound)?.id ?? ""); + } + function reportFailure(cause: unknown, signal: AbortSignal) { + if (signal.aborted) return; + recordOpen(null); + reconnectOnReturn.current = true; + setSnapshot(null); + setCopied(false); + setError(failure(cause)); + setErrorCode(cause instanceof LocalShareError ? cause.code : null); + if (cause instanceof LocalShareError && cause.job?.state === "running") { + void poll(cause.job, signal); + return; + } + setWorking(false); + setProgress(""); + } + async function copy(url: string) { + try { + await navigator.clipboard.writeText(url); + setCopied(true); + shareInteraction(token, { event: "share_link_copied", via: "copy" }); + } catch { + setError("Couldn’t copy. Open the shared page and copy its address."); + } + } + return { + snapshot, + audience, + setAudience, + spaceId, + busy, + error, + errorCode, + copied, + progress, + run, + copy, + }; +} +export type QuickShareModel = ReturnType; diff --git a/scripts/check-cli-share-capture.mjs b/scripts/check-cli-share-capture.mjs new file mode 100644 index 0000000000..4406f01a7f --- /dev/null +++ b/scripts/check-cli-share-capture.mjs @@ -0,0 +1,28 @@ +import assert from "node:assert/strict"; +import { mkdtempSync, readdirSync, readFileSync, rmSync, writeFileSync } from "node:fs"; +import { tmpdir } from "node:os"; +import { join, resolve } from "node:path"; +import { pathToFileURL } from "node:url"; + +// Exercise the bundled CLI, whose import.meta.url differs from the share source tree. +const dist = resolve(process.argv[2]); +const chunk = readdirSync(dist).find((name) => { + if (!name.endsWith(".js")) return false; + const source = readFileSync(join(dist, name), "utf8"); + return /export\s*\{[^}]*\bshareContentFingerprint\b/s.test(source); +}); +assert.ok(chunk, "CLI must expose its bundled source fingerprint to the share command"); +const { shareContentFingerprint } = await import(pathToFileURL(join(dist, chunk)).href); +const project = mkdtempSync(join(tmpdir(), "hyperframes-packed-share-")); +try { + writeFileSync(join(project, "index.html"), "Video"); + const asset = join(project, "café.txt"); + writeFileSync(asset, "first"); + const before = await shareContentFingerprint(project); + assert.match(before, /^[a-f0-9]{64}$/); + writeFileSync(asset, "second"); + assert.notEqual(await shareContentFingerprint(project), before); + console.log("Bundled CLI captures portable source with its policy and Unicode registries."); +} finally { + rmSync(project, { recursive: true, force: true }); +} diff --git a/scripts/package-size-budgets.json b/scripts/package-size-budgets.json index fa4f9fe216..f981c5dd93 100644 --- a/scripts/package-size-budgets.json +++ b/scripts/package-size-budgets.json @@ -4,7 +4,7 @@ "unpacked": 290508 }, "@hyperframes/cli": { - "packed": 8062664, + "packed": 8577627, "unpacked": 25159107 }, "@hyperframes/core": { diff --git a/scripts/studio-runtime-smoke.mjs b/scripts/studio-runtime-smoke.mjs index 4d2843042a..ff9af88220 100644 --- a/scripts/studio-runtime-smoke.mjs +++ b/scripts/studio-runtime-smoke.mjs @@ -23,6 +23,7 @@ function text(body, contentType = "text/plain") { const PROJECT_PATH = `/api/projects/${PROJECT_ID}`; const GET_RESPONSES = new Map([ + ["/api/share/bootstrap", json({ csrf: "s".repeat(43) })], [ "/api/projects", json({ projects: [{ id: PROJECT_ID, dir: "/tmp/smoke-test", title: "Smoke test" }] }), diff --git a/scripts/studio-runtime-smoke.test.mjs b/scripts/studio-runtime-smoke.test.mjs index 3b687069ba..23d37ad3f6 100644 --- a/scripts/studio-runtime-smoke.test.mjs +++ b/scripts/studio-runtime-smoke.test.mjs @@ -13,6 +13,9 @@ function bodyOf(method, path) { } describe("Studio runtime smoke fixtures", () => { + it("bootstraps the sharing entry point without credentials", () => { + assert.deepEqual(bodyOf("GET", "/api/share/bootstrap"), { csrf: "s".repeat(43) }); + }); it("matches the collection and project-detail API schemas", () => { assert.deepEqual(bodyOf("GET", "/api/projects"), { projects: [{ id: "smoke-test", dir: "/tmp/smoke-test", title: "Smoke test" }], diff --git a/scripts/verify-packed-manifests.mjs b/scripts/verify-packed-manifests.mjs index b9827bbc2e..8d964bc233 100644 --- a/scripts/verify-packed-manifests.mjs +++ b/scripts/verify-packed-manifests.mjs @@ -558,6 +558,14 @@ function verifyPackedConsumer(packDir, packedWorkspaces) { if (!cliOutput.toLowerCase().includes("hyperframes")) { throw new Error("Packed CLI help did not identify HyperFrames"); } + execFileSync( + "node", + [ + join(ROOT, "scripts", "check-cli-share-capture.mjs"), + join(fixtureDir, "node_modules", "@hyperframes", "cli", "dist"), + ], + { cwd: fixtureDir, stdio: "inherit", timeout: 30_000 }, + ); console.log(smokeOutput.trim()); console.log( "Verified clean packed consumer install, Node execution, NodeNext declaration check, Vite resolution, and CLI startup.",