mirror of
https://github.com/heygen-com/hyperframes.git
synced 2026-11-19 19:36:04 +00:00
feat(studio): share review pages from local preview (#7140)
Advertise the CLI sharing bridge before bootstrapping it so standalone Studio does not request unsupported routes. Preserve origin and session checks. Budget the intended sharing artifact: clean main packs at 8,060,519 bytes versus 8,162,979 with sharing (8,169,168 in CI). Required policy and Unicode tables, bundled sharing code, and Studio controls account for the growth. Set the packed-only budget to 8,577,627, following the 5% headroom convention; retain the unpacked cap and all package checks.
This commit is contained in:
@@ -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"
|
||||
|
||||
@@ -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.
|
||||
|
||||
@@ -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.
|
||||
|
||||
@@ -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);
|
||||
|
||||
@@ -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);
|
||||
});
|
||||
|
||||
|
||||
@@ -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"),
|
||||
'<main data-composition-id="main" data-width="1920" data-height="1080" data-duration="1"></main>',
|
||||
);
|
||||
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 });
|
||||
}
|
||||
});
|
||||
|
||||
@@ -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 {
|
||||
|
||||
@@ -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);
|
||||
});
|
||||
@@ -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);
|
||||
}
|
||||
|
||||
@@ -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))
|
||||
);
|
||||
},
|
||||
};
|
||||
}
|
||||
@@ -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;
|
||||
}
|
||||
@@ -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"), '<audio src=".media/voice.mp3"></audio>');
|
||||
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();
|
||||
},
|
||||
);
|
||||
@@ -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<ReturnType<typeof versionOnPage>>,
|
||||
): last is NonNullable<typeof last> {
|
||||
return Boolean(
|
||||
last?.checksum &&
|
||||
last.projectId === state.share?.projectId &&
|
||||
last.exportedAt === state.version.last?.exportedAt,
|
||||
);
|
||||
}
|
||||
@@ -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<typeof presentSpaces>[0][number];
|
||||
const [result] = presentSpaces([space]);
|
||||
expect(result?.plan).toBe(plan ?? null);
|
||||
expect(result?.upgradeUrl).toBe(plan === "free" ? "https://hyperframes.dev/pricing" : null);
|
||||
},
|
||||
);
|
||||
@@ -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<ReturnType<ShareService["spaces"]>>,
|
||||
): 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<ReturnType<ShareService["spaces"]>>[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";
|
||||
}
|
||||
@@ -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<void>((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<void>((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" },
|
||||
});
|
||||
});
|
||||
});
|
||||
@@ -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<string, unknown> {
|
||||
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<LocalShareAction, "space" | "videoOnly"> | null {
|
||||
if (!validSpace(space)) return null;
|
||||
if (videoOnly !== undefined && typeof videoOnly !== "boolean") return null;
|
||||
const options: Pick<LocalShareAction, "space" | "videoOnly"> = {};
|
||||
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<ShareService>;
|
||||
const defaultCreate: CreateService = async (path, progress) =>
|
||||
(await import("../share/service.js")).createShareService(path, progress, {
|
||||
surface: "local_studio",
|
||||
pinIdentity: true,
|
||||
});
|
||||
|
||||
async function defaultLogin(): Promise<void> {
|
||||
const { startAuthorizationCodeFlow } = await import("../auth/oauth.js");
|
||||
await startAuthorizationCodeFlow({ timeoutMs: 300_000 });
|
||||
}
|
||||
|
||||
export function mountShareRoutes(
|
||||
app: Hono,
|
||||
projectDir: string,
|
||||
create: CreateService = defaultCreate,
|
||||
login: () => Promise<void> = 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<ReturnType<typeof sessions.get>>,
|
||||
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<ShareService> }) {
|
||||
return shareSessionKey(await (await session.get()).checkSession());
|
||||
}
|
||||
@@ -0,0 +1,31 @@
|
||||
import type { ShareService } from "../share/service.js";
|
||||
import { createShareCsrf } from "./shareBoundary.js";
|
||||
|
||||
export function shareSessionKey(value: Awaited<ReturnType<ShareService["checkSession"]>>) {
|
||||
return JSON.stringify([value.owner, value.heygen, value.heygenApi]);
|
||||
}
|
||||
|
||||
export function createShareSessions(create: () => Promise<ShareService>) {
|
||||
const sessions = new Map<string, ReturnType<typeof session>>();
|
||||
function session() {
|
||||
let service: Promise<ShareService> | 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),
|
||||
};
|
||||
}
|
||||
@@ -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('<meta name="hyperframes-local-share" content="1">');
|
||||
expectClosed();
|
||||
});
|
||||
|
||||
|
||||
@@ -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("<head>", `<head>${headScript}`);
|
||||
}
|
||||
html = html.replace(
|
||||
"<head>",
|
||||
`<head><meta name="hyperframes-local-share" content="1">${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.
|
||||
|
||||
@@ -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);
|
||||
});
|
||||
|
||||
@@ -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 {
|
||||
|
||||
@@ -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 {
|
||||
|
||||
@@ -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<typeof import("@hyperframes/share")>();
|
||||
return {
|
||||
...actual,
|
||||
reviewClient: ({ access }: { access: () => Promise<unknown> }) => ({
|
||||
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<unknown> } }) => {
|
||||
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();
|
||||
});
|
||||
@@ -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();
|
||||
},
|
||||
);
|
||||
|
||||
@@ -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<typeof createShareService>;
|
||||
export type ShareState = Awaited<ReturnType<typeof readStatus>>;
|
||||
|
||||
function hasFailedVersion(version: Awaited<ReturnType<typeof reviewVersion>>): boolean {
|
||||
return Boolean(version.failure && !version.held);
|
||||
}
|
||||
|
||||
@@ -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<void>,
|
||||
@@ -193,12 +193,22 @@ function isLastMetadata(value) {
|
||||
}
|
||||
|
||||
/** @param {Record<string, unknown>} 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<VersionRecord>} */
|
||||
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<Said | null>} */
|
||||
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<VersionRecord["pending"]>} 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<VersionRequest>} 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<VersionRecord["pending"]>} 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<VersionRecord["pending"]>} pending @param {string} dir */
|
||||
function bindRenderKey(pending, dir) {
|
||||
return typeof pending.renderKey === "string"
|
||||
? pending
|
||||
: { ...pending, renderKey: exportKeyOf(dir) };
|
||||
}
|
||||
|
||||
@@ -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);
|
||||
});
|
||||
@@ -78,3 +78,12 @@ export {
|
||||
createStudioMotionRenderBodyScript,
|
||||
type StudioMotionRenderScriptOptions,
|
||||
} from "./helpers/studioMotionRenderScript.js";
|
||||
export type {
|
||||
LocalShareAudience,
|
||||
LocalShareSpace,
|
||||
LocalShareState,
|
||||
LocalShareJob,
|
||||
LocalShareSnapshot,
|
||||
LocalShareAction,
|
||||
LocalShareInteraction,
|
||||
} from "./localShare.js";
|
||||
|
||||
@@ -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" };
|
||||
@@ -517,6 +517,7 @@ export function StudioApp({ readOnlyPreview = false, readOnlyPreviewReason }: St
|
||||
inspectorButtonActive={inspectorButtonActive}
|
||||
inspectorPanelActive={inspectorPanelActive}
|
||||
onExport={handleExport}
|
||||
beforeShare={previewPersistence.waitForPendingDomEditSaves}
|
||||
/>
|
||||
{previewPersistence.domEditSaveQueuePaused && !externalFileChanges.blocked && (
|
||||
<SaveQueuePausedBanner
|
||||
|
||||
@@ -1,4 +1,5 @@
|
||||
import { memo, useContext, type MouseEvent } from "react";
|
||||
import { QuickShare } from "./share/QuickShare";
|
||||
import { Camera } from "../icons/SystemIcons";
|
||||
import { useStudioShellContext } from "../contexts/StudioContext";
|
||||
import { usePanelLayoutContext } from "../contexts/PanelLayoutContext";
|
||||
@@ -19,6 +20,7 @@ interface StudioHeaderProps {
|
||||
inspectorButtonActive: boolean;
|
||||
inspectorPanelActive: boolean;
|
||||
onExport?: () => void;
|
||||
beforeShare?: () => Promise<void>;
|
||||
}
|
||||
|
||||
/**
|
||||
@@ -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 && <ThemeToggle />}
|
||||
<Dock.WindowMenu />
|
||||
<OpenInDesktopButton />
|
||||
<QuickShare beforeShare={beforeShare} />
|
||||
<Tooltip
|
||||
label={
|
||||
ffmpegMissing
|
||||
|
||||
@@ -0,0 +1,548 @@
|
||||
// @vitest-environment happy-dom
|
||||
import React, { act } from "react";
|
||||
import { createRoot, type Root } from "react-dom/client";
|
||||
import { afterEach, beforeEach, expect, it, vi } from "vitest";
|
||||
import type { LocalShareSnapshot, LocalShareJob } from "@hyperframes/studio-server";
|
||||
import type { Button } from "../ui/Button";
|
||||
type ButtonProps = React.ComponentProps<typeof Button>;
|
||||
|
||||
const interaction = vi.hoisted(() => vi.fn());
|
||||
vi.mock("./localShareTelemetry", () => ({ shareInteraction: interaction }));
|
||||
vi.mock("../ui", () => ({
|
||||
Button: ({ children, variant: _variant, ...props }: ButtonProps) => (
|
||||
<button {...props}>{children}</button>
|
||||
),
|
||||
Menu: ({ children }: { children: React.ReactNode }) => <div>{children}</div>,
|
||||
MenuRadioGroup: ({
|
||||
children,
|
||||
value,
|
||||
onValueChange,
|
||||
}: {
|
||||
children: React.ReactNode;
|
||||
value: string;
|
||||
onValueChange: (value: string) => void;
|
||||
}) => (
|
||||
<select
|
||||
aria-label="Who can access"
|
||||
value={value}
|
||||
onChange={(event) => onValueChange(event.target.value)}
|
||||
>
|
||||
<option value="">Choose access</option>
|
||||
{children}
|
||||
</select>
|
||||
),
|
||||
MenuRadioItem: ({ value, disabled }: { value: string; disabled?: boolean }) => (
|
||||
<option value={value} disabled={disabled}>
|
||||
{value === "private" ? "Only you" : value}
|
||||
</option>
|
||||
),
|
||||
Popover: ({ children }: { children: React.ReactNode }) => <div>{children}</div>,
|
||||
}));
|
||||
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<void>) {
|
||||
await act(async () => root.render(<QuickShareContent token={token} beforeShare={beforeShare} />));
|
||||
}
|
||||
async function choose(value: string) {
|
||||
const select = host.querySelector<HTMLSelectElement>('[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<void>((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<HTMLSelectElement>('[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<HTMLSelectElement>('[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<HTMLSelectElement>('[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(<QuickShare />));
|
||||
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(<QuickShare />));
|
||||
expect(fetch).toHaveBeenCalledWith(
|
||||
"/api/share/bootstrap",
|
||||
expect.objectContaining({ method: "GET" }),
|
||||
);
|
||||
} finally {
|
||||
marker.remove();
|
||||
}
|
||||
});
|
||||
@@ -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<void> }) {
|
||||
const [token, setToken] = useState<string | null>(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 (
|
||||
<Popover
|
||||
open={open}
|
||||
onOpenChange={setOpen}
|
||||
align="end"
|
||||
aria-label="Share project"
|
||||
trigger={<Button variant="secondary">Share</Button>}
|
||||
className="w-96 max-w-[calc(100vw-2rem)] rounded-2xl p-4"
|
||||
>
|
||||
{open ? <QuickShareContent token={token} beforeShare={beforeShare} /> : null}
|
||||
</Popover>
|
||||
);
|
||||
}
|
||||
|
||||
export function QuickShareContent({
|
||||
token,
|
||||
beforeShare,
|
||||
}: {
|
||||
token: string;
|
||||
beforeShare?: () => Promise<void>;
|
||||
}) {
|
||||
const model = useQuickShare(token, beforeShare);
|
||||
const { snapshot, progress, error } = model;
|
||||
const url = safeShareUrl(snapshot?.share.url ?? "");
|
||||
const manageUrl = safeShareUrl(snapshot?.share.manageUrl ?? "");
|
||||
return (
|
||||
<div className="flex flex-col gap-3 text-step-13">
|
||||
<div>
|
||||
<h2 className="text-step-15 font-semibold">Share project</h2>
|
||||
<p className="mt-1 text-step-11 text-text-3">Share the latest saved project.</p>
|
||||
</div>
|
||||
{snapshot ? (
|
||||
<>
|
||||
<ShareSettings model={model} snapshot={snapshot} />
|
||||
<ShareNotices model={model} snapshot={snapshot} />
|
||||
<ShareSourceStatus model={model} snapshot={snapshot} />
|
||||
<ShareActions model={model} snapshot={snapshot} url={url} />
|
||||
<SharePlan model={model} snapshot={snapshot} />
|
||||
</>
|
||||
) : null}
|
||||
{!snapshot && !error ? <p role="status">Loading sharing…</p> : null}
|
||||
{progress ? (
|
||||
<p role="status">{progress} You can close this panel; keep Studio running.</p>
|
||||
) : null}
|
||||
<ShareLogin model={model} />
|
||||
{error ? (
|
||||
<p role="alert" className="text-step-11 text-text-2">
|
||||
{error}
|
||||
</p>
|
||||
) : null}
|
||||
<div className="flex flex-wrap items-center gap-2 border-t border-border pt-3">
|
||||
{manageUrl ? (
|
||||
<a
|
||||
href={manageUrl}
|
||||
target="_blank"
|
||||
rel="noreferrer"
|
||||
className="flex h-8 items-center rounded-full px-2 text-step-12 text-text-2 hover:bg-hover"
|
||||
>
|
||||
Manage sharing
|
||||
</a>
|
||||
) : null}
|
||||
{url ? (
|
||||
<a
|
||||
href={url}
|
||||
target="_blank"
|
||||
rel="noreferrer"
|
||||
className="flex h-8 items-center rounded-full px-2 text-step-12 text-text-2 hover:bg-hover"
|
||||
>
|
||||
Open shared page
|
||||
</a>
|
||||
) : null}
|
||||
</div>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
@@ -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 <ShareAudience model={model} snapshot={snapshot} />;
|
||||
}
|
||||
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 ? (
|
||||
<p role="alert" className="text-step-11 text-text-3">
|
||||
{share.failure}
|
||||
</p>
|
||||
) : null}
|
||||
{messages.filter(Boolean).map((message) => (
|
||||
<p key={message} className="text-step-11 text-text-3">
|
||||
{message}
|
||||
</p>
|
||||
))}
|
||||
</>
|
||||
);
|
||||
}
|
||||
export function ShareActions({ model, snapshot, url }: Props & { url: string | null }) {
|
||||
if (snapshot.share.state === "not_shared")
|
||||
return <CreateShare model={model} snapshot={snapshot} />;
|
||||
return (
|
||||
<>
|
||||
{url ? <CopyShare model={model} snapshot={snapshot} url={url} /> : null}
|
||||
{snapshot.versionSharing && snapshot.share.state !== "unavailable" ? (
|
||||
<Button
|
||||
className="h-9 rounded-lg"
|
||||
variant={snapshot.share.changed !== false ? "primary" : "secondary"}
|
||||
disabled={model.busy}
|
||||
onClick={() => void model.run({ action: "update" })}
|
||||
>
|
||||
{(snapshot.job?.state === "failed" || snapshot.share.state === "failed") &&
|
||||
snapshot.share.hasReadyVersion === false
|
||||
? "Create share link"
|
||||
: "Update shared version"}
|
||||
</Button>
|
||||
) : null}
|
||||
<ManageShare model={model} snapshot={snapshot} url={url} />
|
||||
</>
|
||||
);
|
||||
}
|
||||
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 ? (
|
||||
<p className="text-step-11 text-text-3">
|
||||
Sharing isn’t available in the workspace selected at sign-in. Sign in with an accessible
|
||||
workspace to continue.
|
||||
</p>
|
||||
) : null}
|
||||
<Button
|
||||
variant="primary"
|
||||
className="h-9 self-end rounded-lg px-3 text-step-13"
|
||||
disabled={model.busy || !canCreate}
|
||||
onClick={() => {
|
||||
if (model.audience)
|
||||
void model.run({ action: "share", audience: model.audience, space: model.spaceId });
|
||||
}}
|
||||
>
|
||||
Create share link
|
||||
</Button>
|
||||
</>
|
||||
);
|
||||
}
|
||||
function CopyShare({ model, snapshot, url }: Props & { url: string }) {
|
||||
const label = model.copied
|
||||
? "Copied"
|
||||
: snapshot.share.changed !== false
|
||||
? "Copy current shared link"
|
||||
: "Copy link";
|
||||
return (
|
||||
<div className="flex min-w-0 items-center gap-2 rounded-xl border border-border p-2.5">
|
||||
<span
|
||||
className="min-w-0 flex-1 truncate rounded-lg bg-press px-2.5 py-2 font-mono text-step-11 text-text-3"
|
||||
title={url}
|
||||
>
|
||||
{url.replace(/^https:\/\//, "")}
|
||||
</span>
|
||||
<Button
|
||||
className="h-9 shrink-0 rounded-lg px-3 text-step-12"
|
||||
variant={snapshot.share.changed !== false ? "secondary" : "primary"}
|
||||
disabled={model.busy}
|
||||
onClick={() => void model.copy(url)}
|
||||
>
|
||||
<Link size={15} aria-hidden="true" />
|
||||
{label}
|
||||
</Button>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
function ManageShare({ model, snapshot, url }: Props & { url: string | null }) {
|
||||
return (
|
||||
<div className="flex flex-wrap items-center justify-end gap-1">
|
||||
{model.audience && model.audience !== snapshot.share.audience ? (
|
||||
<Button
|
||||
variant="ghost"
|
||||
className="h-8 rounded-full text-step-13"
|
||||
disabled={model.busy}
|
||||
onClick={() => {
|
||||
if (model.audience) void model.run({ action: "access", audience: model.audience });
|
||||
}}
|
||||
>
|
||||
Save access
|
||||
</Button>
|
||||
) : null}
|
||||
{snapshot.share.state === "link_off" ? (
|
||||
<Button disabled={model.busy} onClick={() => void model.run({ action: "on" })}>
|
||||
Turn link on
|
||||
</Button>
|
||||
) : null}
|
||||
{url ? (
|
||||
<Button
|
||||
variant="ghost"
|
||||
className="h-8 rounded-full text-step-13"
|
||||
disabled={model.busy}
|
||||
onClick={() => {
|
||||
if (
|
||||
window.confirm(
|
||||
"Turn off this link? Everyone using the link loses access. Comments are kept.",
|
||||
)
|
||||
)
|
||||
void model.run({ action: "off" });
|
||||
}}
|
||||
>
|
||||
Turn link off
|
||||
</Button>
|
||||
) : null}
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
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 (
|
||||
<>
|
||||
<p className="text-step-11 text-text-3">{message}</p>
|
||||
{recover ? (
|
||||
<Button
|
||||
variant="ghost"
|
||||
className="h-8 rounded-full text-step-13"
|
||||
disabled={model.busy}
|
||||
onClick={() => void model.run({ action: "update", videoOnly: true })}
|
||||
>
|
||||
Retry with video only
|
||||
</Button>
|
||||
) : 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 (
|
||||
<>
|
||||
<Button
|
||||
variant="primary"
|
||||
disabled={model.busy}
|
||||
onClick={() => void model.run({ action: "login" })}
|
||||
>
|
||||
Sign in
|
||||
</Button>
|
||||
<p className="text-step-11 text-text-3">
|
||||
Or run <code>hyperframes auth login</code> in your terminal, then return to Studio. Sharing
|
||||
reconnects automatically.
|
||||
</p>
|
||||
</>
|
||||
);
|
||||
}
|
||||
|
||||
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 (
|
||||
<div className="flex flex-wrap items-center justify-between gap-2 text-step-12">
|
||||
{space && space.limit !== null && space.used !== null ? (
|
||||
<span className="text-text-3 tabular-nums">
|
||||
{space.used} of {space.limit} free share links used
|
||||
</span>
|
||||
) : null}
|
||||
{space?.plan === "free" && allowed ? (
|
||||
<a
|
||||
href={upgrade}
|
||||
target="_blank"
|
||||
rel="noreferrer"
|
||||
className="inline-flex h-8 items-center gap-1 rounded-full px-2 font-semibold text-accent hover:bg-hover"
|
||||
>
|
||||
Upgrade to Pro
|
||||
<ArrowUpRight size={13} aria-hidden="true" />
|
||||
</a>
|
||||
) : null}
|
||||
</div>
|
||||
);
|
||||
}
|
||||
@@ -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 (
|
||||
<Menu
|
||||
aria-label="Who can access"
|
||||
className="w-80 max-w-[calc(100vw-2rem)] rounded-xl p-1.5"
|
||||
trigger={
|
||||
<button
|
||||
type="button"
|
||||
aria-label="Who can access"
|
||||
disabled={model.busy || snapshot.share.state === "unavailable"}
|
||||
className="flex min-h-11 w-full items-center gap-2.5 rounded-xl px-1.5 py-1.5 text-left text-step-13 hover:bg-hover disabled:opacity-40"
|
||||
>
|
||||
<span className="grid size-8 shrink-0 place-items-center rounded-full bg-press text-text-2">
|
||||
<Icon size={16} aria-hidden="true" />
|
||||
</span>
|
||||
<span className="min-w-0 flex-1 font-semibold">
|
||||
{selected?.label ?? "Choose who can access"}
|
||||
</span>
|
||||
<CaretDown size={14} aria-hidden="true" />
|
||||
</button>
|
||||
}
|
||||
>
|
||||
<MenuRadioGroup
|
||||
value={model.audience}
|
||||
onValueChange={(value) => {
|
||||
if (isAudience(value)) model.setAudience(value);
|
||||
}}
|
||||
>
|
||||
{choices.map((value) => {
|
||||
const option = AUDIENCES[value];
|
||||
const OptionIcon = option.icon;
|
||||
return (
|
||||
<MenuRadioItem
|
||||
key={value}
|
||||
value={value}
|
||||
closeOnClick
|
||||
disabled={
|
||||
model.busy ||
|
||||
(!space?.audiences.includes(value) && value !== snapshot.share.audience)
|
||||
}
|
||||
className="h-auto min-h-12 rounded-lg px-2 py-2 text-step-13"
|
||||
>
|
||||
<span className="flex items-center gap-2.5">
|
||||
<span className="grid size-7 shrink-0 place-items-center rounded-full bg-press text-text-2">
|
||||
<OptionIcon size={15} aria-hidden="true" />
|
||||
</span>
|
||||
<span className="min-w-0 leading-snug">
|
||||
<span className="block font-semibold">{option.label}</span>
|
||||
<span className="block whitespace-normal text-step-11 text-text-3">
|
||||
{option.detail}
|
||||
</span>
|
||||
</span>
|
||||
</span>
|
||||
</MenuRadioItem>
|
||||
);
|
||||
})}
|
||||
</MenuRadioGroup>
|
||||
</Menu>
|
||||
);
|
||||
}
|
||||
@@ -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<string, unknown> =>
|
||||
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<unknown> {
|
||||
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<string> {
|
||||
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<LocalShareSnapshot> {
|
||||
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<LocalShareJob> {
|
||||
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<LocalShareJob> {
|
||||
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);
|
||||
}
|
||||
@@ -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" }),
|
||||
}),
|
||||
);
|
||||
});
|
||||
@@ -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(() => {});
|
||||
}
|
||||
@@ -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<string, string> = {
|
||||
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<void>) {
|
||||
const [snapshot, setSnapshot] = useState<LocalShareSnapshot | null>(null);
|
||||
const [audience, setAudience] = useState<LocalShareAudience | "">("");
|
||||
const [spaceId, setSpaceId] = useState("");
|
||||
const [busy, setBusyState] = useState(false);
|
||||
const working = useRef(false);
|
||||
const reconnectOnReturn = useRef(false);
|
||||
const [error, setError] = useState<string | null>(null);
|
||||
const [errorCode, setErrorCode] = useState<string | null>(null);
|
||||
const [copied, setCopied] = useState(false);
|
||||
const opened = useRef(false);
|
||||
const lifetime = useRef<AbortController | null>(null);
|
||||
const timer = useRef<ReturnType<typeof setTimeout> | 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<typeof useQuickShare>;
|
||||
@@ -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"), "<html><body>Video</body></html>");
|
||||
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 });
|
||||
}
|
||||
@@ -4,7 +4,7 @@
|
||||
"unpacked": 290508
|
||||
},
|
||||
"@hyperframes/cli": {
|
||||
"packed": 8062664,
|
||||
"packed": 8577627,
|
||||
"unpacked": 25159107
|
||||
},
|
||||
"@hyperframes/core": {
|
||||
|
||||
@@ -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" }] }),
|
||||
|
||||
@@ -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" }],
|
||||
|
||||
@@ -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.",
|
||||
|
||||
Reference in New Issue
Block a user