fix: the dev Studio's renders follow the received-project rule, and a received project's .env keys never replace the person's own (#8004)

* fix(studio): dev Studio renders apply the received-project rule for outside files

The Vite Studio adapter started every render with files from outside the
project allowed. It now asks the CLI's outsideAssetsAllowed, the same check
the CLI's embedded Studio, hyperframes render and benchmark use. A project
whose received-files record lists code files, or cannot be read, renders
without files from outside the project, and the reason prints with a
[studio] prefix.

The adapter loads the rule from the CLI source through the dev server, as it
already does for background removal. It runs only from a source checkout, so
studio takes no package dependency on the CLI.

* fix(cli): a received project's .env provider key never replaces your own credential

A received project's .env could set OPENROUTER_API_KEY, GEMINI_API_KEY,
GOOGLE_API_KEY or Vertex settings that outranked a vision or Gemini
credential the person set in the shell, so capture, snapshot describe and
media-use speech and music could send content to another account.

After the CLI and capture load a project .env, each provider key it set is
unset when that .env came with a received project (a received-files record
lists it, or a record cannot be read) and the person has their own
credential for a competing provider. One stderr line names the key, the
.env file and the credential used instead.

A person's own project .env keeps its keys and its current precedence, so
an OPENROUTER_API_KEY in a project .env still wins over a Gemini key in the
shell, as the docs describe. Voice needs no change: the person's HeyGen
credential already ranks above ElevenLabs.

* fix(cli,media-use): media-use scripts apply the received .env rule, ElevenLabs included

The media-use audio scripts read the project .env again, so a Gemini key the
CLI had left out came back. They now apply the same rule after loading: a
key from a received project's .env gives way to the person's own credential
for a competing provider. GEMINI_API_KEY and GOOGLE_API_KEY give way to the
person's Gemini key or service account. ELEVENLABS_API_KEY gives way to the
person's HeyGen sign-in, saved key or shell key. A dropped key gets one
stderr line that names the file and the credential used instead.

A received ElevenLabs key that is still used, because the person has no
competing credential, gets one stderr line naming the .env before speech
starts. hyperframes media-use tells the engine which keys it took from a
project .env (HYPERFRAMES_PROJECT_ENV_ORIGINS), so a key the CLI loaded is
not mistaken for the shell's.

When the project's folders are too many to scan for received-files
records, the CLI's note now says the project's origin could not be
checked, instead of calling it a received project.

* refactor(studio): check the shape of the CLI's outside-files rule before calling it

The Vite adapter loads outsideAssetsAllowed from the CLI source at run time.
It now checks that the export is a function and treats only a true result
as allowed, instead of casting the module's export.

* docs(auth): a received project's ElevenLabs key gives way to your HeyGen credential

* test(studio): load the received-project rule before render waits start
This commit is contained in:
Michael Wang
2026-11-17 05:04:15 +00:00
committed by GitHub
parent 00d03a4122
commit 8239fe4702
15 changed files with 516 additions and 14 deletions
+1 -1
View File
@@ -152,7 +152,7 @@ to a shared space with `--space`.
| `HYPERFRAMES_CONFIG_DIR` | HyperFrames settings root: credentials, telemetry and update settings, project links (default `~/.hyperframes`). |
| `HYPERFRAMES_ENV` | `prod` (default) or `dev`; `dev` keeps credentials in a separate `dev/` directory under the root. Hosts and the OAuth client id come from `HEYGEN_API_URL`, `HYPERFRAMES_OAUTH_*` and `HYPERFRAMES_PUBLISHED_PROJECTS_API_URL`. |
| `HYPERFRAMES_OAUTH_CLIENT_ID` | Override the public client ID for a controlled OAuth environment. |
| `ELEVENLABS_API_KEY` | ElevenLabs TTS, used when no HeyGen credential is present. |
| `ELEVENLABS_API_KEY` | ElevenLabs TTS, used when no HeyGen credential is present. A key from a received project's `.env` is never used next to your own HeyGen credential, and a note names the file when it is used. |
| `GEMINI_API_KEY` / `GOOGLE_API_KEY` | Explicit Gemini TTS selection and Lyria music generation; capture descriptions use `GEMINI_API_KEY`. |
| `GOOGLE_APPLICATION_CREDENTIALS` / `GCS_CREDS` | Gemini TTS service-account JSON file path / injected JSON. Used when neither API key is set. |
| `GOOGLE_CLOUD_PROJECT` / `GCLOUD_PROJECT_ID` | Gemini OAuth quota project; first set value wins, then the service account project. |
+4
View File
@@ -404,6 +404,10 @@ For AI image descriptions, set `GEMINI_API_KEY` in a `.env` file
[OpenRouter](https://openrouter.ai) — it wins if both are set, and
`HYPERFRAMES_OPENROUTER_MODEL` overrides the model.
A received project's `.env` (one its received-files record lists) never
replaces a vision or Gemini credential you set in your shell: its competing
keys are ignored, with a note naming the file.
#### Local HTML files
`--local-file` captures an HTML file on disk instead of a URL, for example a
@@ -16,6 +16,7 @@ import { setupAnimationCapture, startCdpAnimationCapture } from "./animationCata
import type { DiscoveredLottie } from "./mediaCapture.js";
import { detectLibraries } from "./contentExtractor.js";
import { loadEnvFile, generateProjectScaffold } from "./scaffolding.js";
import { yieldReceivedProviderKeys } from "../utils/dotEnv.js";
import { captureProtocolTimeoutMs } from "./captureTimeout.js";
import { CAPTURE_PHASE_SCHEMA, DEFAULT_MAX_SCREENSHOTS } from "./types.js";
import type {
@@ -113,6 +114,7 @@ export async function captureWebsiteAttempt(
// Load .env file from repo root if it exists (for GEMINI_API_KEY, etc.)
loadEnvFile(outputDir);
await yieldReceivedProviderKeys((line) => console.error(line));
// Create output directories
ensureCaptureDirSync(outputDir, join(outputDir, "extracted"));
@@ -8,6 +8,8 @@ import {
type VisionCaptionOutcome,
} from "./contentExtractor.js";
import { loadOptionalPackage } from "../utils/optionalPackages.js";
import { yieldReceivedProviderKeys } from "../utils/dotEnv.js";
import { loadEnvFile } from "./scaffolding.js";
const { generateContentMock, clientOptions, sharpState } = vi.hoisted(() => ({
generateContentMock: vi.fn(),
@@ -416,11 +418,42 @@ describe("captionImagesWithGemini — Gemini provider", () => {
afterEach(() => {
generateContentMock.mockReset();
vi.unstubAllGlobals();
vi.unstubAllEnvs();
for (const d of dirs) rmSync(d, { recursive: true, force: true });
dirs.length = 0;
});
it("captions with the shell's Gemini key, never a received project's OpenRouter key", async () => {
const dir = makeProjectWithImages();
dirs.push(dir);
mkdirSync(join(dir, ".hyperframes"));
writeFileSync(
join(dir, ".hyperframes", "received-files.json"),
JSON.stringify({ files: [".env"] }),
);
writeFileSync(join(dir, ".env"), "OPENROUTER_API_KEY=received-key\n");
for (const key of [
"OPENROUTER_API_KEY",
"GOOGLE_API_KEY",
"HYPERFRAMES_VERTEX_PROJECT_ID",
"HYPERFRAMES_VERTEX_SERVICE_ACCOUNT",
"HYPERFRAMES_NO_CAPTURE_DOTENV",
])
vi.stubEnv(key, undefined);
vi.stubEnv("GEMINI_API_KEY", "own-gemini-key");
const fetchMock = vi.fn();
vi.stubGlobal("fetch", fetchMock);
generateContentMock.mockResolvedValue({ text: "A caption." });
loadEnvFile(join(dir, "out"));
await yieldReceivedProviderKeys(() => {});
const captions = await captionImagesWithGemini(dir, () => {}, []);
expect(fetchMock).not.toHaveBeenCalled();
expect(captions).toEqual({ "hero.png": "A caption." });
});
it("terminates captioning when Gemini never settles even if the SDK ignores abort", async () => {
const dir = makeProjectWithImages();
dirs.push(dir);
+2 -1
View File
@@ -70,10 +70,11 @@ if (rootVersionRequested) {
// The working directory is project data: load only the settings a project `.env` may supply,
// before browser selection can observe the environment.
const { loadProjectDotEnv } = await import("./utils/dotEnv.js");
const { loadProjectDotEnv, yieldReceivedProviderKeys } = await import("./utils/dotEnv.js");
const captureEnv = argv[commandWordIndex(argv)] === "capture";
if (!captureEnv || process.env.HYPERFRAMES_NO_CAPTURE_DOTENV !== "1") {
loadProjectDotEnv(process.cwd(), process.env, (line) => console.error(line));
await yieldReceivedProviderKeys((line) => console.error(line));
}
// ── Lazy imports ────────────────────────────────────────────────────────────
@@ -22,6 +22,13 @@ describe("mediaUseEngineEnv", () => {
expect(env).toEqual({ HOME: "/home/u", HYPERFRAMES_CLI_ENTRY: resolve("dist/cli.js") });
});
it("names the folder of each key a project .env set, so the engine weighs it as the CLI did", () => {
const env = mediaUseEngineEnv({}, "", "linux", { ELEVENLABS_API_KEY: "/work/project" });
expect(JSON.parse(env.HYPERFRAMES_PROJECT_ENV_ORIGINS ?? "{}")).toEqual({
ELEVENLABS_API_KEY: "/work/project",
});
});
it("hands nothing over from a TypeScript source entry, which plain node cannot run", () => {
expect(mediaUseEngineEnv({}, "src/cli.ts", "linux")).toEqual({});
expect(mediaUseEngineEnv({}, "", "linux")).toEqual({});
+3
View File
@@ -5,6 +5,7 @@ import { spawnSync } from "node:child_process";
import { existsSync } from "node:fs";
import { finishCommand } from "../utils/commandResult.js";
import { withMediaAuthEnvironment } from "../auth/media-environment.js";
import { PROJECT_ENV_ORIGINS, projectEnvOrigins } from "../utils/dotEnv.js";
import {
skipWorkingDirectoryInExeSearch,
withOnlyTrustedPathFolders,
@@ -83,9 +84,11 @@ export function mediaUseEngineEnv(
env: NodeJS.ProcessEnv,
entry: string | undefined = process.argv[1],
platform: NodeJS.Platform = process.platform,
origins: Record<string, string> = projectEnvOrigins(),
): NodeJS.ProcessEnv {
const scoped = withOnlyTrustedPathFolders(env, platform);
skipWorkingDirectoryInExeSearch(scoped, platform);
if (Object.keys(origins).length > 0) scoped[PROJECT_ENV_ORIGINS] = JSON.stringify(origins);
if (!entry || /\.[cm]?ts$/.test(entry)) return scoped;
return { ...scoped, HYPERFRAMES_CLI_ENTRY: resolve(entry) };
}
+98 -3
View File
@@ -1,8 +1,18 @@
import { describe, expect, it, vi } from "vitest";
import { mkdtempSync, rmSync, writeFileSync } from "node:fs";
import { afterEach, describe, expect, it, vi } from "vitest";
import { mkdirSync, mkdtempSync, rmSync, writeFileSync } from "node:fs";
import { tmpdir } from "node:os";
import { join } from "node:path";
import { applyDotEnv, loadProjectDotEnv } from "./dotEnv.js";
import { applyDotEnv, loadProjectDotEnv, yieldReceivedProviderKeys } from "./dotEnv.js";
const records = vi.hoisted(() => ({ unchecked: false }));
vi.mock("./privateProjectFile.js", async (importOriginal) => {
const actual = await importOriginal<typeof import("./privateProjectFile.js")>();
return {
...actual,
receivedRecordStatus: (dir: string) =>
records.unchecked ? ("unchecked" as const) : actual.receivedRecordStatus(dir),
};
});
describe("applyDotEnv", () => {
it("copies a project's keys without overwriting what is already set", () => {
@@ -144,3 +154,88 @@ describe("loadProjectDotEnv", () => {
}
});
});
describe("yieldReceivedProviderKeys", () => {
const PROVIDER_KEYS = [
"OPENROUTER_API_KEY",
"GEMINI_API_KEY",
"GOOGLE_API_KEY",
"HYPERFRAMES_VERTEX_PROJECT_ID",
"HYPERFRAMES_VERTEX_SERVICE_ACCOUNT",
"GOOGLE_APPLICATION_CREDENTIALS",
"GCS_CREDS",
];
const dirs: string[] = [];
afterEach(() => {
records.unchecked = false;
vi.unstubAllEnvs();
for (const dir of dirs.splice(0)) rmSync(dir, { recursive: true, force: true });
});
/** Loads `env` from a project `.env` into process.env over `shell`; `received` lists the `.env` as received. */
async function load(shell: Record<string, string>, env: string, received: boolean) {
for (const key of PROVIDER_KEYS) vi.stubEnv(key, shell[key]);
const dir = mkdtempSync(join(tmpdir(), "hf-dotenv-provider-"));
dirs.push(dir);
writeFileSync(join(dir, ".env"), env);
if (received) {
mkdirSync(join(dir, ".hyperframes"));
writeFileSync(
join(dir, ".hyperframes", "received-files.json"),
JSON.stringify({ files: [".env"] }),
);
}
const warn = vi.fn();
loadProjectDotEnv(dir, process.env, vi.fn());
await yieldReceivedProviderKeys(warn);
return { dir, warn };
}
it("drops a received .env's OpenRouter key when the shell has a Gemini key", async () => {
const { dir, warn } = await load(
{ GEMINI_API_KEY: "own" },
"OPENROUTER_API_KEY=received\n",
true,
);
expect(process.env.OPENROUTER_API_KEY).toBeUndefined();
expect(process.env.GEMINI_API_KEY).toBe("own");
expect(warn).toHaveBeenCalledWith(
`[hyperframes] .env: ignoring OPENROUTER_API_KEY from a received project (${join(dir, ".env")}); using your own GEMINI_API_KEY`,
);
});
it("drops received Gemini and Vertex keys when the shell has a Vertex or Google credential", async () => {
await load(
{
HYPERFRAMES_VERTEX_SERVICE_ACCOUNT: "/own/sa.json",
GOOGLE_APPLICATION_CREDENTIALS: "/own/sa.json",
},
"GEMINI_API_KEY=received\nHYPERFRAMES_VERTEX_PROJECT_ID=received\n",
true,
);
expect(process.env.GEMINI_API_KEY).toBeUndefined();
expect(process.env.HYPERFRAMES_VERTEX_PROJECT_ID).toBeUndefined();
});
it("keeps a person's own .env OpenRouter key ahead of their shell Gemini key", async () => {
const { warn } = await load({ GEMINI_API_KEY: "own" }, "OPENROUTER_API_KEY=mine\n", false);
expect(process.env.OPENROUTER_API_KEY).toBe("mine");
expect(warn).not.toHaveBeenCalled();
});
it("keeps a received .env key when the person has no credential it competes with", async () => {
const { warn } = await load({}, "OPENROUTER_API_KEY=received\n", true);
expect(process.env.OPENROUTER_API_KEY).toBe("received");
expect(warn).not.toHaveBeenCalled();
});
it("says the project's origin could not be checked when its folders are too many to scan", async () => {
records.unchecked = true;
const { dir, warn } = await load({ GEMINI_API_KEY: "own" }, "OPENROUTER_API_KEY=mine\n", false);
expect(process.env.OPENROUTER_API_KEY).toBeUndefined();
expect(warn).toHaveBeenCalledWith(
`[hyperframes] .env: ignoring OPENROUTER_API_KEY from a project whose origin could not be checked (too many folders to scan) (${join(dir, ".env")}); using your own GEMINI_API_KEY`,
);
});
});
+59
View File
@@ -112,6 +112,65 @@ export function projectEnvDir(name: string): string | undefined {
return set !== undefined && process.env[name] === set.value ? set.sourceDir : undefined;
}
// Each group is one choice between providers: capture and snapshot vision, then Gemini speech and music.
const COMPETING_PROVIDER_KEYS: readonly (readonly string[])[] = [
[
"OPENROUTER_API_KEY",
"GEMINI_API_KEY",
"GOOGLE_API_KEY",
"HYPERFRAMES_VERTEX_PROJECT_ID",
"HYPERFRAMES_VERTEX_SERVICE_ACCOUNT",
],
["GEMINI_API_KEY", "GOOGLE_API_KEY", "GOOGLE_APPLICATION_CREDENTIALS", "GCS_CREDS"],
];
const competitorsOf = (name: string): string[] =>
COMPETING_PROVIDER_KEYS.filter((group) => group.includes(name)).flatMap((group) =>
group.filter((other) => other !== name && Boolean(process.env[other])),
);
async function untrustedEnvOrigin(dir: string): Promise<string | null> {
const { receivedFiles, receivedRecordStatus } = await import("./privateProjectFile.js");
if (receivedRecordStatus(dir) === "unchecked")
return "a project whose origin could not be checked (too many folders to scan)";
return receivedFiles(dir)(".env") ? "a received project" : null;
}
/** Unsets each provider key a received project's `.env` set while the person has their own credential for a competing provider. */
export async function yieldReceivedProviderKeys(warn: (line: string) => void): Promise<void> {
const contested = [...projectEnvValues.keys()].filter(
(name) => projectEnvDir(name) !== undefined && competitorsOf(name).length > 0,
);
const origins = new Map<string, string | null>();
for (const dir of new Set(contested.map((name) => projectEnvDir(name) ?? ""))) {
origins.set(dir, await untrustedEnvOrigin(dir));
}
const originOf = (name: string) => origins.get(projectEnvDir(name) ?? "") ?? null;
for (const name of contested.filter((name) => originOf(name) !== null)) {
const own = competitorsOf(name).find((other) => originOf(other) === null);
if (own === undefined) continue;
const dir = projectEnvDir(name) ?? "";
const origin = originOf(name);
delete process.env[name];
projectEnvValues.delete(name);
warn(
`[hyperframes] .env: ignoring ${name} from ${origin} (${join(dir, ".env")}); using your own ${own}`,
);
}
}
export const PROJECT_ENV_ORIGINS = "HYPERFRAMES_PROJECT_ENV_ORIGINS";
/** The folder of each key a project `.env` set, for the scripts the CLI launches to weigh the same way. */
export function projectEnvOrigins(): Record<string, string> {
return Object.fromEntries(
[...projectEnvValues.keys()].flatMap((name) => {
const dir = projectEnvDir(name);
return dir === undefined ? [] : [[name, dir]];
}),
);
}
export function loadProjectDotEnv(
dir: string,
env: NodeJS.ProcessEnv,
+33 -3
View File
@@ -3,9 +3,10 @@ import {
cancelAndVerifyArtifacts,
} from "../../test-utils/renderCancellation";
import { afterEach, describe, expect, it, vi } from "vitest";
import { mkdtempSync, readFileSync, rmSync, writeFileSync } from "node:fs";
import { mkdirSync, mkdtempSync, readFileSync, rmSync, writeFileSync } from "node:fs";
import { tmpdir } from "node:os";
import { join } from "node:path";
import { fileURLToPath } from "node:url";
import { createServer, type ViteDevServer } from "vite";
import { createProjectSignatureCache, createViteAdapter } from "./vite.adapter";
@@ -28,15 +29,22 @@ afterEach(async () => {
for (const dir of dirs.splice(0)) rmSync(dir, { recursive: true, force: true });
});
const RECEIVED_RENDER = fileURLToPath(
new URL("../cli/src/utils/receivedRender.ts", import.meta.url),
);
type RenderOptions = Parameters<ReturnType<typeof createViteAdapter>["startRender"]>[0];
async function fixture(extra: Partial<RenderOptions> = {}) {
async function fixture(extra: Partial<RenderOptions> = {}, setup?: (dir: string) => void) {
const dir = mkdtempSync(join(tmpdir(), "hf-vite-gif-"));
dirs.push(dir);
setup?.(dir);
server = await createServer({
configFile: false,
server: { middlewareMode: true, watch: null, ws: false },
});
// Loads the received-project rule before the render starts, so a cold load on CI isn't timed by the waits below.
await server.ssrLoadModule(RECEIVED_RENDER);
const adapter = createViteAdapter(
dir,
server,
@@ -56,7 +64,7 @@ async function fixture(extra: Partial<RenderOptions> = {}) {
return { dir, state, outputPath, metaPath: join(dir, "out.meta.json") };
}
describe("Vite GIF rendering", () => {
describe("Vite GIF rendering", { timeout: 30_000 }, () => {
it("forwards loop count and writes a sidecar without overwriting the GIF", async () => {
producer.executeRenderJob.mockImplementation(async (_job, _dir, outputPath: string) => {
writeFileSync(outputPath, "GIF89a");
@@ -105,4 +113,26 @@ describe("Studio dev server render jobs", { timeout: 30_000 }, () => {
await vi.waitFor(() => expect(state.status, state.error).toBe("complete"), RENDER_DONE);
expect(producer.createRenderJob.mock.calls[0]?.[0]).not.toHaveProperty("pageMotionBlur");
});
it.each([
["allows", "a project of your own", [] as string[], true],
["refuses", "a project whose received files include HTML", ["index.html"], false],
])("%s files outside the project for %s", async (_verb, _name, received, allowed) => {
producer.executeRenderJob.mockResolvedValue(undefined);
const warn = vi.spyOn(console, "warn").mockImplementation(() => {});
const { state } = await fixture({ format: "mp4" }, (dir) => {
writeFileSync(join(dir, "index.html"), '<img src="../outside.png">');
if (received.length === 0) return;
mkdirSync(join(dir, ".hyperframes"));
writeFileSync(
join(dir, ".hyperframes", "received-files.json"),
JSON.stringify({ files: received }),
);
});
await vi.waitFor(() => expect(state.status, state.error).toBe("complete"), RENDER_DONE);
expect(producer.createRenderJob).toHaveBeenCalledWith(
expect.objectContaining({ allowOutsideProjectAssets: allowed }),
);
warn.mockRestore();
});
});
+18 -1
View File
@@ -165,6 +165,19 @@ export function createViteAdapter(
return _bundler;
};
// The CLI's received-project rule, loaded from source: this adapter only runs in a source checkout.
const outsideAssetsAllowed = async (projectDir: string, entryFile: string | undefined) => {
const mod = await server.ssrLoadModule(
resolve(__dirname, "../cli/src/utils/receivedRender.ts"),
);
const decide: unknown = mod.outsideAssetsAllowed;
if (typeof decide !== "function")
throw new Error("receivedRender.ts has no outsideAssetsAllowed");
return (
decide(projectDir, entryFile, (line: string) => console.warn(`[studio] ${line}`)) === true
);
};
const getProducerModule = async () => {
if (!_producerModuleLoader) {
_producerModuleLoader = createRetryingModuleLoader(async () => {
@@ -349,6 +362,10 @@ export function createViteAdapter(
if (systemChrome) process.env.PRODUCER_HEADLESS_SHELL_PATH = systemChrome;
}
const { createRenderJob, executeRenderJob } = await getProducerModule();
const allowOutsideProjectAssets = await outsideAssetsAllowed(
opts.project.dir,
opts.composition,
);
const renderBodyScripts = createStudioDevRenderBodyScripts(opts.project.dir);
const job = createRenderJob({
fps: opts.fps,
@@ -362,7 +379,7 @@ export function createViteAdapter(
...encoderJobOptions(opts),
...(opts.useGpu ? { useGpu: true } : {}),
...(opts.pageMotionBlur ? { pageMotionBlur: opts.pageMotionBlur } : {}),
allowOutsideProjectAssets: true,
allowOutsideProjectAssets,
});
const onProgress = (j: { progress: number; currentStage?: string }) => {
state.progress = j.progress;
+1 -1
View File
@@ -18,7 +18,7 @@
"files": 13
},
"media-use": {
"hash": "d96a749d23f71589",
"hash": "2784d98fa34ffc2e",
"files": 128
},
"remotion-to-hyperframes": {
+134 -2
View File
@@ -11,9 +11,9 @@ import { fetchMedia } from "../../../scripts/lib/media-fetch.mjs";
// heygen CLI; plain HTTP needs $HEYGEN_ALLOW_HTTP=1, as there.
// Vendored so the skill ships standalone. Pure node.
import { mkdirSync, readFileSync, writeFileSync } from "node:fs";
import { lstatSync, mkdirSync, readFileSync, realpathSync, statSync, writeFileSync } from "node:fs";
import { homedir } from "node:os";
import { dirname, join, resolve } from "node:path";
import { dirname, join, relative, resolve, sep } from "node:path";
export const HEYGEN_BASE = "https://api.heygen.com/v3";
@@ -88,8 +88,140 @@ function projectKeyDir(name) {
return set !== undefined && set.val === process.env[name] ? set.dir : undefined;
}
const GEMINI_CREDENTIALS = [
"GEMINI_API_KEY",
"GOOGLE_API_KEY",
"GOOGLE_APPLICATION_CREDENTIALS",
"GCS_CREDS",
];
// The hyperframes CLI names the folder whose .env set each key it passes on, so a key it loaded is not the shell's.
function inheritProjectKeyOrigins() {
let origins;
try {
origins = JSON.parse(process.env.HYPERFRAMES_PROJECT_ENV_ORIGINS || "{}");
} catch {
return;
}
for (const name of [...GEMINI_CREDENTIALS, "ELEVENLABS_API_KEY"]) {
const dir = origins?.[name];
if (typeof dir === "string" && process.env[name] && !projectEnvValues.has(name))
projectEnvValues.set(name, { val: process.env[name], dir });
}
}
function isFile(path) {
try {
return statSync(path).isFile();
} catch {
return false;
}
}
function fileIdentity(path) {
try {
const stat = lstatSync(path, { bigint: true });
return stat.ino === 0n ? null : `${stat.dev}:${stat.ino}`;
} catch {
return null;
}
}
// The CLI's received-files rule: a record at or above `dir` lists its .env (by path or as the same file on disk), or a
// record there cannot be read. → "listed" | "unreadable" | null.
function receivedEnvFile(dir) {
let start;
try {
start = realpathSync(dir);
} catch {
start = resolve(dir);
}
const envIdentity = fileIdentity(join(dir, ".env"));
for (let root = start; ; root = dirname(root)) {
const record = join(root, ".hyperframes", "received-files.json");
if (root === start || isFile(record)) {
let files;
try {
files = JSON.parse(readFileSync(record, "utf8")).files;
} catch (error) {
if (root !== start || !["ENOENT", "ENOTDIR"].includes(error.code)) return "unreadable";
files = [];
}
if (!Array.isArray(files)) return "unreadable";
const key = relative(root, join(start, ".env")).split(sep).join("/").normalize("NFC");
const listed = files.some((file) => {
const entry = String(file).normalize("NFC");
return (
entry === key || (envIdentity !== null && fileIdentity(join(root, entry)) === envIdentity)
);
});
if (listed) return "listed";
}
if (dirname(root) === root) return null;
}
}
const RECEIVED_ORIGIN = {
listed: "a received project",
unreadable: "a project whose received-files record could not be read",
};
// How a project key's .env is not the person's own, or null when it is theirs or the key is not from a .env.
function untrustedOrigin(name) {
const dir = projectKeyDir(name);
const kind = dir === undefined ? null : receivedEnvFile(dir);
return kind === null ? null : RECEIVED_ORIGIN[kind];
}
// The person's own credential that the provider of `name` competes with, named for the note; undefined when none.
function ownCompetingCredential(name) {
if (name !== "ELEVENLABS_API_KEY")
return GEMINI_CREDENTIALS.find(
(other) => other !== name && process.env[other] && untrustedOrigin(other) === null,
);
if (process.env.HEYGEN_ACCESS_TOKEN) return "HEYGEN_ACCESS_TOKEN";
const heygenKey = ["HEYGEN_API_KEY", "HYPERFRAMES_API_KEY"].find(
(other) => process.env[other] && untrustedOrigin(other) === null,
);
if (heygenKey) return heygenKey;
return storedCredential() ? "saved HeyGen credentials" : undefined;
}
// A received project's provider key gives way to the person's own credential for a competing provider.
function yieldReceivedProviderKeys() {
for (const name of ["GEMINI_API_KEY", "GOOGLE_API_KEY", "ELEVENLABS_API_KEY"]) {
const origin = untrustedOrigin(name);
const own = origin === null ? undefined : ownCompetingCredential(name);
if (own === undefined) continue;
const dir = projectKeyDir(name);
delete process.env[name];
projectEnvValues.delete(name);
process.stderr.write(
`[hyperframes] .env: ignoring ${name} from ${origin} (${join(dir, ".env")}); using your own ${own}\n`,
);
}
}
let elevenlabsKeyNoted = false;
// Says once, before ElevenLabs speaks, that the key came from a received project's .env.
export function noteReceivedElevenLabsKey() {
const origin = untrustedOrigin("ELEVENLABS_API_KEY");
if (origin === null || elevenlabsKeyNoted) return;
elevenlabsKeyNoted = true;
process.stderr.write(
`[hyperframes] Using ELEVENLABS_API_KEY from ${join(projectKeyDir("ELEVENLABS_API_KEY"), ".env")}, the .env of ${origin}: speech goes to that key's ElevenLabs account.\n`,
);
}
// Walk up ≤5 dirs from startDir; load the first .env (shell env always wins).
export function loadEnvFromDir(startDir) {
inheritProjectKeyOrigins();
loadFirstEnvFile(startDir);
yieldReceivedProviderKeys();
}
function loadFirstEnvFile(startDir) {
let dir = resolve(startDir);
for (let i = 0; i < 5; i++) {
const text = envFileText(join(dir, ".env"));
@@ -13,6 +13,7 @@ import {
heygenJSON,
heygenMessage,
loadEnvFromDir,
noteReceivedElevenLabsKey,
} from "./heygen.mjs";
const HEYGEN_ENV = [
@@ -625,3 +626,111 @@ test("a refused HyperFrames-plan call becomes one line with the billing command"
"bad voice",
);
});
const PROVIDER_ENV = [
"GEMINI_API_KEY",
"GOOGLE_API_KEY",
"GOOGLE_APPLICATION_CREDENTIALS",
"GCS_CREDS",
"ELEVENLABS_API_KEY",
"HYPERFRAMES_PROJECT_ENV_ORIGINS",
];
// Runs fn(project, notes) with HeyGen and provider variables unset, no saved credentials, the given shell variables
// set and a project folder whose .env holds `env`; `received` lists that .env in a received-files record.
function withProviderProject({ shell = {}, env, received }, fn) {
return withCleanHeygenEnv(() => {
const previous = Object.fromEntries(PROVIDER_ENV.map((name) => [name, process.env[name]]));
const project = mkdtempSync(join(tmpdir(), "hf-media-provider-"));
const notes = [];
const write = process.stderr.write;
try {
for (const name of PROVIDER_ENV) delete process.env[name];
process.env.HYPERFRAMES_CONFIG_DIR = join(project, "no-config");
Object.assign(process.env, shell);
writeFileSync(join(project, ".env"), env);
if (received) {
mkdirSync(join(project, ".hyperframes"));
writeFileSync(
join(project, ".hyperframes", "received-files.json"),
JSON.stringify({ files: [".env"] }),
);
}
process.stderr.write = (line) => notes.push(String(line));
fn(project, notes);
} finally {
process.stderr.write = write;
for (const [name, value] of Object.entries(previous)) {
if (value === undefined) delete process.env[name];
else process.env[name] = value;
}
rmSync(project, { recursive: true, force: true });
}
});
}
test("loadEnvFromDir leaves out a received .env's Gemini key when the shell has Gemini credentials", () => {
withProviderProject(
{
shell: { GOOGLE_APPLICATION_CREDENTIALS: "/own/sa.json" },
env: "GEMINI_API_KEY=received\n",
received: true,
},
(project, notes) => {
loadEnvFromDir(project);
assert.equal(process.env.GEMINI_API_KEY, undefined);
assert.match(
notes.join(""),
/ignoring GEMINI_API_KEY from a received project .*GOOGLE_APPLICATION_CREDENTIALS/,
);
},
);
});
test("loadEnvFromDir keeps a person's own .env Gemini key next to their shell credentials", () => {
withProviderProject(
{ shell: { GOOGLE_APPLICATION_CREDENTIALS: "/own/sa.json" }, env: "GEMINI_API_KEY=mine\n" },
(project, notes) => {
loadEnvFromDir(project);
assert.equal(process.env.GEMINI_API_KEY, "mine");
assert.deepEqual(notes, []);
},
);
});
test("loadEnvFromDir leaves out a received .env's ElevenLabs key when the person has a HeyGen key", () => {
withProviderProject(
{ shell: { HEYGEN_API_KEY: "own" }, env: "ELEVENLABS_API_KEY=received\n", received: true },
(project) => {
loadEnvFromDir(project);
assert.equal(process.env.ELEVENLABS_API_KEY, undefined);
},
);
});
test("a key the CLI took from a received .env gives way the same as one the script read", () => {
withProviderProject({ env: "", received: true }, (project) => {
process.env.HEYGEN_API_KEY = "own";
process.env.ELEVENLABS_API_KEY = "received";
process.env.HYPERFRAMES_PROJECT_ENV_ORIGINS = JSON.stringify({ ELEVENLABS_API_KEY: project });
loadEnvFromDir(project);
assert.equal(process.env.ELEVENLABS_API_KEY, undefined);
});
});
test("a received .env's ElevenLabs key with no competing credential is used, with a note naming the file", () => {
withProviderProject(
{ env: "ELEVENLABS_API_KEY=received\n", received: true },
(project, notes) => {
loadEnvFromDir(project);
assert.equal(process.env.ELEVENLABS_API_KEY, "received");
noteReceivedElevenLabsKey();
noteReceivedElevenLabsKey();
assert.equal(notes.length, 1);
assert.match(
notes[0],
/Using ELEVENLABS_API_KEY from .*\.env, the \.env of a received project/,
);
},
);
});
+12 -2
View File
@@ -20,7 +20,13 @@ import { spawn, spawnSync } from "node:child_process";
import { existsSync, mkdirSync, mkdtempSync, readFileSync, rmSync, writeFileSync } from "node:fs";
import { tmpdir } from "node:os";
import { dirname, isAbsolute, join } from "node:path";
import { heygenAuthHeaders, heygenCredential, heygenJSON, heygenMessage } from "./heygen.mjs";
import {
heygenAuthHeaders,
heygenCredential,
heygenJSON,
heygenMessage,
noteReceivedElevenLabsKey,
} from "./heygen.mjs";
import { pythonInvocation } from "./python.mjs";
import { synthesizeGemini } from "./gemini-tts.mjs";
import { geminiConfigured } from "./gemini-auth.mjs";
@@ -51,9 +57,13 @@ export function pickProvider(userProvider) {
if (userProvider === "heygen" && !heygenAvailable()) heygenAuthHeaders();
if (userProvider === "elevenlabs" && !process.env.ELEVENLABS_API_KEY)
throw new Error("provider=elevenlabs but $ELEVENLABS_API_KEY is not set");
if (userProvider === "elevenlabs") noteReceivedElevenLabsKey();
return userProvider;
}
return heygenAvailable() ? "heygen" : elevenlabsAvailable() ? "elevenlabs" : "kokoro";
if (heygenAvailable()) return "heygen";
if (!elevenlabsAvailable()) return "kokoro";
noteReceivedElevenLabsKey();
return "elevenlabs";
}
// ── voice resolution ──────────────────────────────────────────────────────────