fix(cli): a project .env key is used only when nothing is saved (#7848)

A HEYGEN_API_KEY or HYPERFRAMES_API_KEY that a project .env sets now comes
after every credential the person saved or exported. The CLI resolver, the
media environment and the media-use skill use it only when there is no saved
login, no saved API key and no key in the shell. When one is used, a single
stderr line names the .env file.

An expired, foreign-client, unreadable or refused login now raises the login
error instead of switching to a project .env key, whether or not the folder
has a received-files record. A key exported in the shell, or set by the app
that launched the CLI, keeps its current place, and the host gateway path is
unchanged.
This commit is contained in:
Michael Wang
2026-11-15 17:59:08 +00:00
committed by GitHub
parent 96cc8cb852
commit de1ce68988
14 changed files with 265 additions and 295 deletions
+4 -2
View File
@@ -37,7 +37,7 @@ Signing in is the same OAuth step as creating an account — new users land on t
</Step>
</Steps>
HyperFrames uses its own public OAuth client and stores credentials in `~/.hyperframes/credentials` (mode `0600`). Sign in again after upgrading from the shared HeyGen login. The separate [`heygen` CLI](https://github.com/heygen-com/heygen-cli) keeps its own login in `~/.heygen`; HyperFrames does not move or delete it. A signed-in HyperFrames session wins over `HEYGEN_API_KEY` in the environment. The environment key is used only when no session is signed in, when HeyGen refuses to refresh the session, or when a host app routes calls through its own gateway. An expired session never selects a saved API key instead. An API key, from the environment or `auth login --api-key`, selects API-key billing.
HyperFrames uses its own public OAuth client and stores credentials in `~/.hyperframes/credentials` (mode `0600`). Sign in again after upgrading from the shared HeyGen login. The separate [`heygen` CLI](https://github.com/heygen-com/heygen-cli) keeps its own login in `~/.heygen`; HyperFrames does not move or delete it. A signed-in HyperFrames session wins over `HEYGEN_API_KEY` in the environment. The environment key is used only when no session is signed in, when HeyGen refuses to refresh the session, or when a host app routes calls through its own gateway. An expired session never selects a saved API key instead. A key from the project `.env` is used only when no session or API key is saved and the environment sets none, and the CLI names that `.env` file on stderr when it uses one. An API key, from the environment or `auth login --api-key`, selects API-key billing.
`auth status` verifies identity. For a dedicated HyperFrames OAuth login it reports the billing product, but the HyperFrames balance is unavailable here: `/v3/users/me` returns generic HeyGen account billing fields. Those raw fields remain in JSON and are not presented as the HyperFrames balance. Host-injected or custom-client OAuth is reported as an unverified billing product.
@@ -58,8 +58,10 @@ sound retrieval. It resolves first-match-wins:
4. `HEYGEN_API_KEY` — environment variable
5. `HYPERFRAMES_API_KEY` — alias, for parity with other tools
6. An API key saved in `~/.hyperframes/credentials` by `hyperframes auth login --api-key`
7. A key from a nearby project `.env`, only when nothing is saved
A nearby project `.env` can supply the keys, but never `HEYGEN_API_BASE`. Point at a different config directory
A nearby project `.env` can supply the keys, but never `HEYGEN_API_BASE`. Its key never replaces a saved
session or API key, including an expired session, and the scripts name the `.env` file on stderr when they use it. Point at a different config directory
with `HYPERFRAMES_CONFIG_DIR`. The scripts can't refresh a session; the `hyperframes` CLI's own commands use the same
order and refresh an expired session first. See the [CLI reference](/packages/cli). When `media-use` invokes the separate `heygen` executable, it supplies an isolated temporary credential containing the selected access token. That helper cannot refresh a HyperFrames grant or pick up another HeyGen login.
+8 -3
View File
@@ -116,7 +116,8 @@ Some commands add their own fields next to `error`, such as `findings` from
**The project `.env`.** The `.env` in the current directory sets only the CLI's own
settings: `HEYGEN_API_KEY`, `HYPERFRAMES_API_KEY`, `ELEVENLABS_API_KEY`, `FIGMA_TOKEN`, and the
vision keys, models, Vertex settings and timeout, and the telemetry opt-outs `HYPERFRAMES_NO_TELEMETRY` and `DO_NOT_TRACK`. A variable already in your environment wins. Any
other key in the file is ignored, and one line on stderr names them.
other key in the file is ignored, and one line on stderr names them. A HeyGen key from the `.env` is used only
when no login or API key is saved (see [`auth`](#hyperframes-auth)).
**Flags, not prompts.** A missing required flag fails immediately with a usage
example rather than waiting for input. These commands can ask questions on a TTY:
@@ -2586,9 +2587,13 @@ First match wins:
1. `HEYGEN_ACCESS_TOKEN` (an OAuth token a host app injects; never refreshed or saved)
2. Your `hyperframes auth login` session in `~/.hyperframes/credentials`. An expired session is refreshed first.
3. `HEYGEN_API_KEY`
3. `HEYGEN_API_KEY` set in your environment
4. `HYPERFRAMES_API_KEY` (a HyperFrames alias for the same thing)
5. An API key saved with `hyperframes auth login --api-key`
6. A `HEYGEN_API_KEY` or `HYPERFRAMES_API_KEY` from the project `.env`, only when nothing is saved
A project `.env` key never replaces an expired session or a saved key. When the CLI
uses one, it prints a line on stderr that names the `.env` file.
A signed-in session wins over an API key in the environment. The environment key
is used instead when HeyGen refuses to refresh the session, or when `HEYGEN_API_URL` or
@@ -2655,7 +2660,7 @@ hyperframes auth logout --yes # no prompt
| Variable | Description |
| --------------------- | ------------------------------------------------ |
| `HEYGEN_API_KEY` | API key, used when no session is signed in. Wins over a key saved with `--api-key`. |
| `HEYGEN_API_KEY` | API key, used when no session is signed in. Wins over a key saved with `--api-key`. A project `.env` key is used only when nothing is saved. |
| `HYPERFRAMES_API_KEY` | Alias for `HEYGEN_API_KEY`. |
| `HEYGEN_ACCESS_TOKEN` | OAuth token from a host app; used first, never refreshed. |
| `HEYGEN_API_URL` | API base URL (default `https://api.heygen.com`). |
+49 -28
View File
@@ -72,37 +72,58 @@ describe("media-use authentication", () => {
});
});
it("passes the saved API key, not a HEYGEN_API_KEY from a received project .env", async () => {
await writeStore({ api_key: "saved-key" });
const project = join(fixture.dir, "project");
await fs.mkdir(join(project, ".hyperframes"), { recursive: true });
await fs.writeFile(join(project, ".env"), "HEYGEN_API_KEY=received-key-3\n");
await fs.writeFile(
join(project, ".hyperframes", "received-files.json"),
JSON.stringify({ files: [".env"] }),
);
/** Loads `name=key` from a project `.env`; `record` writes its received-files record. */
async function projectEnvKey(key: string, record?: string, name = "HEYGEN_API_KEY") {
const project = await fs.mkdtemp(join(fixture.dir, "project-"));
await fs.writeFile(join(project, ".env"), `${name}=${key}\n`);
if (record !== undefined) {
await fs.mkdir(join(project, ".hyperframes"));
await fs.writeFile(join(project, ".hyperframes", "received-files.json"), record);
}
loadProjectDotEnv(project, process.env, () => {});
await withMediaAuthEnvironment(async (env) => {
expect(env.HEYGEN_API_KEY).toBe("saved-key");
});
});
}
it("leaves out a received project .env key when the saved login expired", async () => {
await persistFreshOAuth({
access_token: "expired",
expires_at: new Date(Date.now() - 60 * 1000).toISOString(),
describe.each([
["a folder with no received-files record", undefined],
["a received folder", JSON.stringify({ files: [".env"] })],
])("with a project .env key from %s", (_, record) => {
it("passes the saved API key, and neither project key", async () => {
await writeStore({ api_key: "saved-key" });
await projectEnvKey(`media-saved-${String(record)}`, record);
await projectEnvKey(`media-alias-${String(record)}`, record, "HYPERFRAMES_API_KEY");
await withMediaAuthEnvironment(async (env) => {
expect(env.HEYGEN_API_KEY).toBe("saved-key");
expect(env.HYPERFRAMES_API_KEY).toBeUndefined();
});
});
const project = join(fixture.dir, "project");
await fs.mkdir(join(project, ".hyperframes"), { recursive: true });
await fs.writeFile(join(project, ".env"), "HEYGEN_API_KEY=received-key-4\n");
await fs.writeFile(
join(project, ".hyperframes", "received-files.json"),
JSON.stringify({ files: [".env"] }),
);
loadProjectDotEnv(project, process.env, () => {});
await withMediaAuthEnvironment(async (env) => {
expect(env.HEYGEN_API_KEY).toBeUndefined();
expect(env.HEYGEN_ACCESS_TOKEN).toBeUndefined();
it("leaves the key out when the saved login expired", async () => {
await persistFreshOAuth({
access_token: "expired",
expires_at: new Date(Date.now() - 60 * 1000).toISOString(),
});
await projectEnvKey(`media-expired-${String(record)}`, record);
await withMediaAuthEnvironment(async (env) => {
expect(env.HEYGEN_API_KEY).toBeUndefined();
expect(env.HEYGEN_ACCESS_TOKEN).toBeUndefined();
});
});
it("fails without a request on that key when HeyGen refuses to refresh the login", async () => {
await persistFreshOAuth({
access_token: "expired",
refresh_token: "hf-refresh",
expires_at: new Date(Date.now() - 60 * 1000).toISOString(),
});
await projectEnvKey(`media-refused-${String(record)}`, record);
const fetchMock = vi.fn(async () => new Response("invalid_grant", { status: 400 }));
vi.stubGlobal("fetch", fetchMock);
const run = vi.fn();
await expect(withMediaAuthEnvironment(run)).rejects.toMatchObject({
code: "REFRESH_FAILED",
});
expect(run).not.toHaveBeenCalled();
expect(fetchMock).toHaveBeenCalledOnce();
});
});
@@ -63,6 +63,7 @@ export async function withMediaAuthEnvironment<T>(run: (env: NodeJS.ProcessEnv)
);
} else if (credential?.type === "api_key") {
env.HEYGEN_API_KEY = credential.key;
delete env.HYPERFRAMES_API_KEY;
delete env.HEYGEN_ACCESS_TOKEN;
} else {
delete env.HEYGEN_ACCESS_TOKEN;
+74 -63
View File
@@ -137,7 +137,7 @@ describe("auth/resolver", () => {
key: string,
received?: string,
name = "HEYGEN_API_KEY",
): Promise<void> {
): Promise<string> {
const project = await fs.mkdtemp(join(dir, "project-"));
await fs.writeFile(join(project, ".env"), `${name}=${key}\n`);
if (received !== undefined) {
@@ -145,21 +145,20 @@ describe("auth/resolver", () => {
await fs.writeFile(join(project, ".hyperframes", "received-files.json"), received);
}
loadProjectDotEnv(project, process.env, () => {});
return project;
}
it("keeps a person's own project .env key ahead of the saved API key", async () => {
await projectEnvKey("own-key-1");
await writeStore({ api_key: "file-key" });
expect(await resolveCredential()).toEqual({ type: "api_key", key: "own-key-1", source: "env" });
});
const RECEIVED = JSON.stringify({ files: [".env"] });
/** A cloned or copied folder has no received-files record; a received one lists its `.env`. */
const PROJECT_KINDS = [
["a folder with no received-files record", undefined],
["a received folder", RECEIVED],
] as const;
it.each([
["lists it", JSON.stringify({ files: [".env"] })],
["cannot be read", "{oops"],
])(
"puts the saved API key ahead of a project .env key when the received record %s",
it.each([...PROJECT_KINDS, ["an unreadable received-files record", "{oops"]] as const)(
"puts the saved API key ahead of a project .env key from %s",
async (_, record) => {
await projectEnvKey(`received-key-${record.length}`, record);
await projectEnvKey(`saved-first-${String(record)}`, record);
await writeStore({ api_key: "file-key" });
expect(await resolveCredential()).toEqual({
type: "api_key",
@@ -173,75 +172,87 @@ describe("auth/resolver", () => {
["HEYGEN_API_KEY", "HYPERFRAMES_API_KEY", "env_alias"],
["HYPERFRAMES_API_KEY", "HEYGEN_API_KEY", "env"],
] as const)(
"uses the shell's key over a received .env's %s, with or without a saved key",
async (receivedName, shellName, source) => {
"uses the shell's key over a project .env's %s, with or without a saved key",
async (projectName, shellName, source) => {
process.env[shellName] = "shell-key";
await projectEnvKey("received-key-5", JSON.stringify({ files: [".env"] }), receivedName);
await projectEnvKey(`project-key-${projectName}`, undefined, projectName);
expect(await resolveCredential()).toEqual({ type: "api_key", key: "shell-key", source });
await writeStore({ api_key: "file-key" });
expect(await resolveCredential()).toEqual({ type: "api_key", key: "shell-key", source });
},
);
it("uses a received project .env key when no credential is saved, and says so once", async () => {
it.each(PROJECT_KINDS)(
"uses a project .env key from %s when nothing is saved, and names the file once",
async (_, record) => {
const stderr = vi.spyOn(process.stderr, "write").mockImplementation(() => true);
try {
const project = await projectEnvKey(`only-key-${String(record)}`, record);
expect(await resolveCredential()).toEqual({
type: "api_key",
key: `only-key-${String(record)}`,
source: "env",
});
await resolveCredential();
expect(stderr.mock.calls.map(([line]) => String(line))).toEqual([
`[hyperframes] Using HEYGEN_API_KEY from this folder's .env (${join(project, ".env")}): uploads and renders go to that key's HeyGen account.\n`,
]);
} finally {
stderr.mockRestore();
}
},
);
describe.each(PROJECT_KINDS)("a project .env key from %s", (_, record) => {
it.each([
["expired without a refresh token", { access_token: "stale", expires_at: "2020-01-01Z" }],
["from another OAuth client", { access_token: "foreign", client_id: "shared-heygen-cli" }],
])("never replaces a saved login that is %s", async (_why, oauth) => {
await projectEnvKey(`login-key-${String(record)}`, record);
await writeStore({ oauth });
await expect(resolveCredential()).rejects.toMatchObject({ code: "LOGIN_EXPIRED" });
});
it("never replaces a credentials file that cannot be read", async () => {
await projectEnvKey(`broken-key-${String(record)}`, record);
await fs.writeFile(join(dir, "credentials"), "{not valid", { mode: 0o600 });
await expect(resolveCredential()).rejects.toMatchObject({ code: "INVALID_STORE" });
});
it("never replaces a login HeyGen refused to refresh", async () => {
await projectEnvKey(`refused-key-${String(record)}`, record);
await writeStore({
oauth: { access_token: "at", refresh_token: "rt", expires_at: anHourAgo() },
});
const refused = ErrRefreshFailed("invalid_grant", { refused: true });
await expect(afterRefreshFailure(refused, "rt")).rejects.toBe(refused);
expect(await resolveCredential()).toMatchObject({ type: "oauth", refreshable: true });
});
});
it("keeps a key the launching app set over a project .env, as a shell key", async () => {
const stderr = vi.spyOn(process.stderr, "write").mockImplementation(() => true);
try {
await projectEnvKey("received-key-2", JSON.stringify({ files: [".env"] }));
process.env["HEYGEN_API_KEY"] = "host-key";
await projectEnvKey("project-key-under-host");
await writeStore({ api_key: "file-key" });
expect(process.env["HEYGEN_API_KEY"]).toBe("host-key");
expect(await resolveCredential()).toEqual({
type: "api_key",
key: "received-key-2",
key: "host-key",
source: "env",
});
await resolveCredential();
expect(stderr.mock.calls.map(([line]) => String(line))).toEqual([
"[hyperframes] Using HEYGEN_API_KEY from this folder's .env: uploads and renders go to that key's HeyGen account.\n",
]);
expect(stderr).not.toHaveBeenCalled();
} finally {
stderr.mockRestore();
}
});
it.each([
[
"expired without a refresh token",
{ access_token: "stale-at", expires_at: "2020-01-01T00:00:00Z" },
],
["from another OAuth client", { access_token: "foreign", client_id: "shared-heygen-cli" }],
])(
"asks to log in again over a received .env key when the saved login is %s",
async (_, oauth) => {
await projectEnvKey("received-key-3", JSON.stringify({ files: [".env"] }));
await writeStore({ oauth });
await expect(resolveCredential()).rejects.toSatisfy(isAuthError);
},
);
it("says the credentials file cannot be read rather than use a received .env key", async () => {
await projectEnvKey("received-key-6", JSON.stringify({ files: [".env"] }));
await fs.writeFile(join(dir, "credentials"), "{not valid", { mode: 0o600 });
await expect(resolveCredential()).rejects.toMatchObject({ code: "INVALID_STORE" });
});
it("keeps a person's own project .env key in place of a broken credentials file", async () => {
await projectEnvKey("own-key-3");
await fs.writeFile(join(dir, "credentials"), "{not valid", { mode: 0o600 });
expect(await resolveCredential()).toEqual({ type: "api_key", key: "own-key-3", source: "env" });
});
it("keeps a person's own project .env key in place of a login that expired", async () => {
await projectEnvKey("own-key-2");
await writeStore({ oauth: { access_token: "stale-at", expires_at: anHourAgo() } });
expect(await resolveCredential()).toEqual({ type: "api_key", key: "own-key-2", source: "env" });
});
it("never lets a received .env key replace a login HeyGen refused to refresh", async () => {
await projectEnvKey("received-key-4", JSON.stringify({ files: [".env"] }));
await writeStore({
oauth: { access_token: "at", refresh_token: "rt", expires_at: anHourAgo() },
});
const refused = ErrRefreshFailed("invalid_grant", { refused: true });
await expect(afterRefreshFailure(refused, "rt")).rejects.toBe(refused);
expect(await resolveCredential()).toMatchObject({ type: "oauth", refreshable: true });
it("gives a host app's gateway the project .env key when the host set none", async () => {
process.env["HEYGEN_API_URL"] = "http://127.0.0.1:4100";
await projectEnvKey("gateway-project-key");
await writeStore({ oauth: { access_token: "fresh-at", expires_at: inOneHour() } });
expect(await resolveCredential()).toMatchObject({ key: "gateway-project-key" });
});
it("falls through to HYPERFRAMES_API_KEY", async () => {
+42 -43
View File
@@ -2,18 +2,20 @@
* Chain resolver for HyperFrames credentials. First usable source wins:
* 1. `HEYGEN_ACCESS_TOKEN` env (an OAuth token a host app injects)
* 2. The stored login: fresh, or expired with a refresh token
* 3. `HEYGEN_API_KEY` env, then `HYPERFRAMES_API_KEY`, unless a received project `.env` set it
* 4. The API key saved in `~/.hyperframes/credentials`, else a received project `.env` key
* 3. `HEYGEN_API_KEY` env, then `HYPERFRAMES_API_KEY`, when the shell set it
* 4. The API key saved in `~/.hyperframes/credentials`
* 5. A key a project `.env` set, only when nothing is saved
*
* The env key goes first for a host app's gateway, and once HeyGen refused to refresh the login.
* A broken store gives way to an env key not from a received `.env`, else surfaces `ErrInvalidStore`.
* Neither a saved API key nor a received `.env` key replaces an expired login (60s skew).
* A broken store gives way to a shell key, else surfaces `ErrInvalidStore`.
* Neither a saved API key nor a project `.env` key replaces an expired login (60s skew).
*/
import { isHeaderSafe, readStore } from "./store.js";
import { ErrInvalidStore, ErrLoginExpired, ErrNotConfigured, isAuthError } from "./errors.js";
import { assertOAuthIdentity } from "./config.js";
import { apiBaseUrl } from "./client.js";
import { join } from "node:path";
import { projectEnvDir } from "../utils/dotEnv.js";
type EnvSource = "env" | "env_alias" | "env_oauth";
@@ -60,7 +62,9 @@ export async function resolveCredential(opts: ResolveOptions = {}): Promise<Reso
async function resolveFromSources(opts: ResolveOptions): Promise<ResolvedCredential> {
const now = (opts.now ?? (() => new Date()))();
const envKey = await envApiKey();
const shellKey = envApiKey(false);
const projectKey = envApiKey(true);
const envKey = shellKey ?? projectKey;
// A gateway takes the key its host app set and must never receive an OAuth token.
if (envKey && !heygenApiHost()) return envKey;
@@ -68,21 +72,22 @@ async function resolveFromSources(opts: ResolveOptions): Promise<ResolvedCredent
if (accessToken) {
return { type: "oauth", access_token: accessToken, source: "env_oauth", refreshable: false };
}
if (envKey && loginRefreshFailed) return envKey;
return await fromStore(now, envKey);
if (shellKey && loginRefreshFailed) return shellKey;
return await fromStore(now, shellKey, projectKey);
}
/** The stored login, else the env key, else the stored API key. */
async function fromStore(
now: Date,
envKey: ApiKeyCredential | undefined,
shellKey: ApiKeyCredential | undefined,
projectKey: ApiKeyCredential | undefined,
): Promise<ResolvedCredential> {
const store = await readStore().catch(async (err: unknown) => {
if (envKey && !(await fromReceivedProjectEnv(envKey))) return null;
const store = await readStore().catch((err: unknown) => {
if (shellKey) return null;
throw err;
});
if (!store || store.source === "absent") {
if (envKey) return envKey;
const key = shellKey ?? projectKey;
if (key) return key;
throw ErrNotConfigured();
}
const { credentials, source } = store;
@@ -91,34 +96,29 @@ async function fromStore(
credentials.oauth && boundToThisClient(credentials.oauth)
? pickOAuth(credentials.oauth, now, fileSource)
: null;
return login ?? (await apiKeyWithoutLogin(credentials, fileSource, envKey));
return login ?? apiKeyWithoutLogin(credentials, fileSource, shellKey, projectKey);
}
async function apiKeyWithoutLogin(
function apiKeyWithoutLogin(
credentials: Awaited<ReturnType<typeof readStore>>["credentials"],
source: CredentialSource,
envKey: ApiKeyCredential | undefined,
): Promise<ApiKeyCredential> {
const saved = Boolean(credentials.oauth || credentials.api_key);
if (envKey && !(saved && (await fromReceivedProjectEnv(envKey)))) return envKey;
shellKey: ApiKeyCredential | undefined,
projectKey: ApiKeyCredential | undefined,
): ApiKeyCredential {
if (shellKey) return shellKey;
if (projectKey && !credentials.oauth && !credentials.api_key) return projectKey;
return storedApiKey(credentials, source);
}
async function fromReceivedProjectEnv(credential: ResolvedCredential): Promise<boolean> {
const name = envCredentialVar(credential.source);
const dir = credential.type === "api_key" && name ? projectEnvDir(name) : undefined;
if (dir === undefined) return false;
const { receivedFiles } = await import("../utils/privateProjectFile.js");
return receivedFiles(dir)(".env");
}
let projectKeyNoted = false;
async function noteProjectKey(credential: ResolvedCredential): Promise<ResolvedCredential> {
if (!projectKeyNoted && (await fromReceivedProjectEnv(credential))) {
function noteProjectKey(credential: ResolvedCredential): ResolvedCredential {
const name = envCredentialVar(credential.source);
const dir = credential.type === "api_key" && name ? projectEnvDir(name) : undefined;
if (dir !== undefined && !projectKeyNoted) {
projectKeyNoted = true;
process.stderr.write(
`[hyperframes] Using ${envCredentialVar(credential.source)} from this folder's .env: uploads and renders go to that key's HeyGen account.\n`,
`[hyperframes] Using ${name} from this folder's .env (${join(dir, ".env")}): uploads and renders go to that key's HeyGen account.\n`,
);
}
return credential;
@@ -136,17 +136,16 @@ function storedApiKey(
throw ErrNotConfigured();
}
/** The first env key the person set, else the first one a received project `.env` set. */
async function envApiKey(): Promise<ApiKeyCredential | undefined> {
let received: ApiKeyCredential | undefined;
/** The first env key the shell set, or with `fromProject` the first one a project `.env` set. */
function envApiKey(fromProject: boolean): ApiKeyCredential | undefined {
for (const source of ["env", "env_alias"] as const) {
const key = headerSafeEnv(ENV_CREDENTIAL_VAR[source]);
if (!key) continue;
const credential: ApiKeyCredential = { type: "api_key", key, source };
if (!(await fromReceivedProjectEnv(credential))) return credential;
received ??= credential;
const name = ENV_CREDENTIAL_VAR[source];
const key = headerSafeEnv(name);
if (key && (projectEnvDir(name) !== undefined) === fromProject) {
return { type: "api_key", key, source };
}
}
return received;
return undefined;
}
/** False when `HEYGEN_API_URL` or `HEYGEN_API_BASE` names a host app's gateway, not HeyGen. */
@@ -174,9 +173,9 @@ function boundToThisClient(tokens: Parameters<typeof assertOAuthIdentity>[0]): b
let loginRefreshFailed = false;
/**
* After refreshing `refreshToken` failed: a login another process stored since, else an env key not from a received
* `.env` when HeyGen refused the grant (it then replaces the login for this process), else the error. A network or
* server error, or a reply the CLI couldn't read, throws: the login may still work, and the next call refreshes again.
* After refreshing `refreshToken` failed: a login another process stored since, else the shell's env key when HeyGen
* refused the grant (it then replaces the login for this process), else the error. A network or server error, or a
* reply the CLI couldn't read, throws: the login may still work, and the next call refreshes again.
*/
export async function afterRefreshFailure(
err: unknown,
@@ -192,8 +191,8 @@ export async function afterRefreshFailure(
}
}
if (!err.refused && err.code !== "LOGIN_EXPIRED") throw err;
const key = await envApiKey();
if (!key || (await fromReceivedProjectEnv(key))) throw err;
const key = envApiKey(false);
if (!key) throw err;
loginRefreshFailed = true;
return key;
}
+1 -1
View File
@@ -38,7 +38,7 @@ ${c.bold("SUBCOMMANDS:")}
${c.accent("logout")} ${c.dim("Remove the stored credential (--keep-api-key for OAuth-only).")}
${c.bold("ENV VARS:")}
${c.accent("HEYGEN_API_KEY")} API key; used when no login is active (or it can't refresh), before a saved key. A received project's .env key is used only when no login or key is saved.
${c.accent("HEYGEN_API_KEY")} API key; used when no login is active (or it can't refresh), before a saved key. A project's .env key is used only when no login or key is saved and the shell sets none.
${c.accent("HYPERFRAMES_API_KEY")} Alias for HEYGEN_API_KEY.
${c.accent("HEYGEN_ACCESS_TOKEN")} OAuth token from a host app; used first, never refreshed or saved.
${c.accent("HEYGEN_API_URL")} Override the API base URL (default https://api.heygen.com).
+2 -2
View File
@@ -10,7 +10,7 @@
"files": 80
},
"hyperframes-cli": {
"hash": "5e65e3f7835475fb",
"hash": "4ecb93b795a81101",
"files": 13
},
"hyperframes-registry": {
@@ -18,7 +18,7 @@
"files": 13
},
"media-use": {
"hash": "7a02692533d2f833",
"hash": "fe57eec6df8af903",
"files": 125
},
"remotion-to-hyperframes": {
+1 -1
View File
@@ -32,7 +32,7 @@ npx hyperframes auth refresh # force-refresh an OAuth token before a
npx hyperframes auth logout # clear the stored credential
```
Credential resolution order (first match wins): `HEYGEN_ACCESS_TOKEN` (an OAuth token a host app injects; never refreshed or saved), then the `hyperframes auth login` session in `~/.hyperframes/credentials` (refreshed when expired), then `HEYGEN_API_KEY`, then `HYPERFRAMES_API_KEY`, then a key saved with `auth login --api-key`. A key that a received project's `.env` sets is used only when no login or key is saved, never in place of an expired session. A signed-in session wins over an env key; the env key is used if HeyGen refuses to refresh the session or `HEYGEN_API_URL` points at a host app's gateway. `auth status` shows which one is in use; `auth logout` makes the env key win. `HYPERFRAMES_ENV=dev` selects the dev client, OAuth/API hosts and `~/.hyperframes/dev/credentials` together. `HYPERFRAMES_CONFIG_DIR` overrides the credentials root. `HEYGEN_API_URL` overrides the API host.
Credential resolution order (first match wins): `HEYGEN_ACCESS_TOKEN` (an OAuth token a host app injects; never refreshed or saved), then the `hyperframes auth login` session in `~/.hyperframes/credentials` (refreshed when expired), then `HEYGEN_API_KEY`, then `HYPERFRAMES_API_KEY` set in the shell, then a key saved with `auth login --api-key`, then a key that a project's `.env` sets. A project `.env` key is used only when no login or key is saved and the shell sets none, never in place of an expired session, and the CLI names that `.env` file on stderr when it uses one. A signed-in session wins over an env key; the env key is used if HeyGen refuses to refresh the session or `HEYGEN_API_URL` points at a host app's gateway. `auth status` shows which one is in use; `auth logout` makes the env key win. `HYPERFRAMES_ENV=dev` selects the dev client, OAuth/API hosts and `~/.hyperframes/dev/credentials` together. `HYPERFRAMES_CONFIG_DIR` overrides the credentials root. `HEYGEN_API_URL` overrides the API host.
## The render pipeline
@@ -4,13 +4,13 @@
Run `npx hyperframes auth status` to see what's configured and which engines a workflow will use (see the skill's **Preflight** section). Keys resolve in this order — **first match wins**:
| Provider | Resolution order (first non-empty wins) | Local deps when used |
| -------------------------------- | ---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | ------------------------------------------------ |
| **HeyGen** (TTS + BGM retrieval) | `$HEYGEN_ACCESS_TOKEN` → the `~/.hyperframes/credentials` login → `$HEYGEN_API_KEY` → `$HYPERFRAMES_API_KEY` → a saved API key (`$HYPERFRAMES_CONFIG_DIR` overrides the root; dev uses `dev/`) | none (REST) |
| **ElevenLabs** (TTS fallback) | `$ELEVENLABS_API_KEY` | `pip install elevenlabs` |
| **Lyria** (BGM fallback) | `$GEMINI_API_KEY` → `$GOOGLE_API_KEY` | `pip install google-genai` |
| **Kokoro** (TTS, no key) | always — final voice fallback | `pip install kokoro-onnx soundfile` |
| **MusicGen** (BGM, no key) | always — final music fallback | `pip install transformers torch soundfile numpy` |
| Provider | Resolution order (first non-empty wins) | Local deps when used |
| -------------------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | ------------------------------------------------ |
| **HeyGen** (TTS + BGM retrieval) | `$HEYGEN_ACCESS_TOKEN` → the `~/.hyperframes/credentials` login → `$HEYGEN_API_KEY` → `$HYPERFRAMES_API_KEY` → a saved API key → a project `.env` key when nothing is saved (`$HYPERFRAMES_CONFIG_DIR` overrides the root; dev uses `dev/`) | none (REST) |
| **ElevenLabs** (TTS fallback) | `$ELEVENLABS_API_KEY` | `pip install elevenlabs` |
| **Lyria** (BGM fallback) | `$GEMINI_API_KEY` → `$GOOGLE_API_KEY` | `pip install google-genai` |
| **Kokoro** (TTS, no key) | always — final voice fallback | `pip install kokoro-onnx soundfile` |
| **MusicGen** (BGM, no key) | always — final music fallback | `pip install transformers torch soundfile numpy` |
`hyperframes auth login` (browser OAuth) is the recommended setup: one sign-in, every project, no per-repo `.env`. An OAuth login is sent as `Authorization: Bearer`; an API key as `X-Api-Key`; only OAuth is tagged with `X-HeyGen-Source: cli`. The server decides HyperFrames eligibility and charges; API keys use API billing. An expired or foreign OAuth session requires refresh/sign-in and never selects a saved API key. With no HeyGen credential, voice/BGM run fully locally (Kokoro / MusicGen) — `hyperframes auth status` and `hyperframes doctor` both report whether those local deps are installed.
+6 -5
View File
@@ -60,20 +60,21 @@ no CLI provider plumbing:
The script resolves a HeyGen credential the same way the CLI does — first source
wins: a host-injected OAuth `$HEYGEN_ACCESS_TOKEN` → an unexpired login in
`~/.hyperframes/credentials` → `$HEYGEN_API_KEY` → `$HYPERFRAMES_API_KEY` → a
project `.env` (auto-loaded, walks up ≤5 dirs) → an API key saved in
`~/.hyperframes/credentials` (isolated from heygen-cli;
`~/.hyperframes/credentials` → `$HEYGEN_API_KEY` → `$HYPERFRAMES_API_KEY` set in
the shell → an API key saved in `~/.hyperframes/credentials` → a key from a
project `.env` (auto-loaded, walks up ≤5 dirs), used only when nothing is saved
(credentials isolated from heygen-cli;
`$HYPERFRAMES_CONFIG_DIR` overrides the root; `HYPERFRAMES_ENV=dev` uses `dev/`). An OAuth login is sent as
`Authorization: Bearer`; an API key as `X-Api-Key`; only OAuth includes
`X-HeyGen-Source: cli`. The server decides HyperFrames eligibility and charges;
explicit API keys use API billing. An expired or foreign OAuth session gives way
to an env key that a received project's `.env` did not set; without one it stops
to a key set in the shell, never to a project `.env` key; without one it stops
rather than selecting a saved API key, with a hint to run `npx hyperframes auth refresh`
(or `auth login` for a session from another OAuth client).
```bash
# Only needed if you haven't run `npx hyperframes auth login`:
export HEYGEN_API_KEY=... # or put it in a project .env
export HEYGEN_API_KEY=... # a project .env key is used only when nothing is saved
# Synthesize + capture word timestamps in one call (skips a Whisper pass)
node skills/media-use/audio/scripts/heygen-tts.mjs \
+18 -72
View File
@@ -4,16 +4,16 @@ import { fetchMedia } from "../../../scripts/lib/media-fetch.mjs";
// usable source wins — a host gateway ($HEYGEN_API_BASE with its own
// $HEYGEN_API_KEY) → a host-injected OAuth $HEYGEN_ACCESS_TOKEN (Bearer) →
// the live login in ~/.hyperframes/credentials → $HEYGEN_API_KEY /
// $HYPERFRAMES_API_KEY → the API key saved in ~/.hyperframes/credentials →
// a key from a nearby .env that came in with a received project. An expired login gives way to the person's own
// env key, never to the saved API key or a received .env key ($HYPERFRAMES_CONFIG_DIR overrides the dir).
// $HYPERFRAMES_API_KEY from the shell → the API key saved in ~/.hyperframes/credentials →
// a key from a nearby project .env, only when nothing is saved. An expired login gives way to the shell's
// env key, never to the saved API key or a project .env key ($HYPERFRAMES_CONFIG_DIR overrides the dir).
// $HEYGEN_API_BASE moves every request to that host, as it does for the
// heygen CLI; plain HTTP needs $HEYGEN_ALLOW_HTTP=1, as there.
// Vendored so the skill ships standalone. Pure node.
import { lstatSync, mkdirSync, readFileSync, realpathSync, statSync, writeFileSync } from "node:fs";
import { mkdirSync, readFileSync, writeFileSync } from "node:fs";
import { homedir } from "node:os";
import { dirname, join, relative, resolve, sep } from "node:path";
import { dirname, join, resolve } from "node:path";
export const HEYGEN_BASE = "https://api.heygen.com/v3";
@@ -82,65 +82,11 @@ const PROJECT_ENV_KEYS = new Set([
const projectEnvValues = new Map();
let projectKeyNoted = false;
function isFile(path) {
try {
return statSync(path).isFile();
} catch {
return false;
}
}
// The CLI's received-files rule: a received-files record at or above `dir` that lists the file
// (by path or as the same file on disk), or that cannot be read, makes it received.
function recordFiles(root, ownFolder) {
const record = join(root, ".hyperframes", "received-files.json");
if (!ownFolder && !isFile(record)) return null;
try {
return { files: JSON.parse(readFileSync(record, "utf8")).files };
} catch (error) {
return ownFolder && ["ENOENT", "ENOTDIR"].includes(error.code) ? null : { files: undefined };
}
}
function fileIdentity(path) {
try {
const stat = lstatSync(path, { bigint: true });
return stat.ino === 0n ? null : `${stat.dev}:${stat.ino}`;
} catch {
return null;
}
}
function listsEnvFile(files, root, start, envIdentity) {
if (!Array.isArray(files)) return true;
const key = relative(root, join(start, ".env")).split(sep).join("/").normalize("NFC");
return files.some((file) => {
const entry = String(file).normalize("NFC");
return (
entry === key || (envIdentity !== null && fileIdentity(join(root, entry)) === envIdentity)
);
});
}
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 = recordFiles(root, root === start);
if (record && listsEnvFile(record.files, root, start, envIdentity)) return true;
if (dirname(root) === root) return false;
}
}
const receivedProjectKey = (name, key) => {
// The folder whose .env set `name`, while the environment still holds the value it set.
function projectKeyDir(name) {
const set = projectEnvValues.get(name);
return set?.val === key && receivedEnvFile(set.dir);
};
return set !== undefined && set.val === process.env[name] ? set.dir : undefined;
}
// Walk up ≤5 dirs from startDir; load the first .env (shell env always wins).
export function loadEnvFromDir(startDir) {
@@ -191,21 +137,21 @@ function resolveCredential() {
const accessToken = process.env.HEYGEN_ACCESS_TOKEN;
if (accessToken) return { headers: { Authorization: `Bearer ${accessToken}` } };
const envNames = ["HEYGEN_API_KEY", "HYPERFRAMES_API_KEY"].filter((name) => process.env[name]);
const envName =
envNames.find((name) => !receivedProjectKey(name, process.env[name])) ?? envNames[0];
const envKey = envName && process.env[envName];
const fromProject = envName !== undefined && receivedProjectKey(envName, envKey);
const shellName = envNames.find((name) => projectKeyDir(name) === undefined);
const stored = storedCredential();
// A live login wins over an env key; an expired, foreign or unreadable store gives way only to the person's own.
// A live login wins over a shell key; an expired, foreign or unreadable store gives way only to a shell key.
if (stored?.headers && "Authorization" in stored.headers) return stored;
if (!envKey || (fromProject && stored)) return stored;
if (fromProject && !projectKeyNoted) {
if (shellName) return { headers: { "X-Api-Key": process.env[shellName] } };
// A project .env key is used only when nothing is saved.
const projectName = envNames[0];
if (stored || !projectName) return stored;
if (!projectKeyNoted) {
projectKeyNoted = true;
process.stderr.write(
`[hyperframes] Using ${envName} from this folder's .env: generated media goes to that key's HeyGen account.\n`,
`[hyperframes] Using ${projectName} from the project .env (${join(projectKeyDir(projectName), ".env")}): generated media goes to that key's HeyGen account.\n`,
);
}
return { headers: { "X-Api-Key": envKey } };
return { headers: { "X-Api-Key": process.env[projectName] } };
}
// The credential saved in ~/.hyperframes/credentials: { headers } | { expired: true, foreign? } | { unreadable } | null.
@@ -161,7 +161,7 @@ test("a live login wins over HEYGEN_API_KEY; an expired one gives way to it", ()
});
});
// Runs fn(dir, notes) with a temp credentials dir and a project whose .env sets name=key.
// Runs fn(dir, notes, project) with a temp credentials dir and a project whose .env sets name=key.
function withProjectEnv(key, received, fn, name = "HEYGEN_API_KEY") {
withCleanHeygenEnv(() => {
const dir = mkdtempSync(join(tmpdir(), "heygen-cred-"));
@@ -177,7 +177,7 @@ function withProjectEnv(key, received, fn, name = "HEYGEN_API_KEY") {
writeFileSync(join(project, ".hyperframes", "received-files.json"), received);
}
loadEnvFromDir(project);
fn(dir, notes);
fn(dir, notes, project);
} finally {
process.stderr.write = write;
rmSync(dir, { recursive: true, force: true });
@@ -186,41 +186,37 @@ function withProjectEnv(key, received, fn, name = "HEYGEN_API_KEY") {
});
}
test("a person's own project .env key stays ahead of the saved API key", () => {
withProjectEnv("hg_own", undefined, (dir, notes) => {
writeFileSync(join(dir, "credentials"), JSON.stringify({ api_key: "saved-wallet" }));
assert.deepEqual(heygenCredential(), { headers: { "X-Api-Key": "hg_own" } });
assert.deepEqual(notes, []);
});
});
// A cloned or copied folder has no received-files record; a received one lists its .env.
const PROJECT_KINDS = [
["a folder with no received-files record", undefined],
["a received folder", JSON.stringify({ files: [".env"] })],
];
for (const [why, record] of [
["lists it", JSON.stringify({ files: [".env"] })],
["cannot be read", "{oops"],
]) {
test(`a received .env key gives way to the saved API key when the record ${why}`, () => {
withProjectEnv("hg_received", record, (dir) => {
for (const [kind, record] of [...PROJECT_KINDS, ["an unreadable received-files record", "{oops"]]) {
test(`a project .env key from ${kind} gives way to the saved API key`, () => {
withProjectEnv("hg_project", record, (dir, notes) => {
writeFileSync(join(dir, "credentials"), JSON.stringify({ api_key: "saved-wallet" }));
assert.deepEqual(heygenCredential(), { headers: { "X-Api-Key": "saved-wallet" } });
assert.deepEqual(notes, []);
});
});
}
for (const [receivedName, shellName] of [
for (const [projectName, shellName] of [
["HEYGEN_API_KEY", "HYPERFRAMES_API_KEY"],
["HYPERFRAMES_API_KEY", "HEYGEN_API_KEY"],
]) {
test(`the shell's ${shellName} wins over a received .env's ${receivedName}, with or without a saved key`, () => {
test(`the shell's ${shellName} wins over a project .env's ${projectName}, with or without a saved key`, () => {
withProjectEnv(
"hg_received",
JSON.stringify({ files: [".env"] }),
"hg_project",
undefined,
(dir) => {
process.env[shellName] = "hg_shell";
assert.deepEqual(heygenCredential(), { headers: { "X-Api-Key": "hg_shell" } });
writeFileSync(join(dir, "credentials"), JSON.stringify({ api_key: "saved-wallet" }));
assert.deepEqual(heygenCredential(), { headers: { "X-Api-Key": "hg_shell" } });
},
receivedName,
projectName,
);
});
}
@@ -283,14 +279,18 @@ test("an unreadable record in the project's own folder counts its .env as receiv
assert.equal(key, "saved-wallet");
});
test("a received .env key still works with no saved credential, and is named once", () => {
withProjectEnv("hg_received", JSON.stringify({ files: [".env"] }), (_dir, notes) => {
assert.deepEqual(heygenCredential(), { headers: { "X-Api-Key": "hg_received" } });
heygenCredential();
assert.deepEqual(notes, [
"[hyperframes] Using HEYGEN_API_KEY from this folder's .env: generated media goes to that key's HeyGen account.\n",
]);
});
test("a project .env key works with no saved credential, and the process names its file once", () => {
const lines = [];
for (const [, record] of PROJECT_KINDS) {
withProjectEnv("hg_project", record, (_dir, notes, project) => {
assert.deepEqual(heygenCredential(), { headers: { "X-Api-Key": "hg_project" } });
heygenCredential();
lines.push(...notes.map((line) => line.replace(join(project, ".env"), "<file>")));
});
}
assert.deepEqual(lines, [
"[hyperframes] Using HEYGEN_API_KEY from the project .env (<file>): generated media goes to that key's HeyGen account.\n",
]);
});
for (const [why, oauth, state, hint] of [
@@ -307,50 +307,34 @@ for (const [why, oauth, state, hint] of [
/another OAuth client or environment — run `npx hyperframes auth login`/,
],
]) {
test(`a received .env key never replaces a saved login that is ${why}`, () => {
withProjectEnv("hg_received", JSON.stringify({ files: [".env"] }), (dir, notes) => {
const login = {
token_endpoint: "https://api2.heygen.com/v1/oauth/token",
access_token: "at_login",
...oauth,
};
writeFileSync(join(dir, "credentials"), JSON.stringify({ oauth: login }));
assert.deepEqual(heygenCredential(), state);
assert.throws(() => heygenAuthHeaders(), hint);
for (const [kind, record] of PROJECT_KINDS) {
test(`a project .env key from ${kind} never replaces a saved login that is ${why}`, () => {
withProjectEnv("hg_project", record, (dir, notes) => {
const login = {
token_endpoint: "https://api2.heygen.com/v1/oauth/token",
access_token: "at_login",
...oauth,
};
writeFileSync(join(dir, "credentials"), JSON.stringify({ oauth: login }));
assert.deepEqual(heygenCredential(), state);
assert.throws(() => heygenAuthHeaders(), hint);
assert.deepEqual(notes, []);
});
});
}
}
for (const [kind, record] of PROJECT_KINDS) {
test(`a malformed credentials file refuses a project .env key from ${kind} and says to fix that file`, () => {
withProjectEnv("hg_project", record, (dir, notes) => {
writeFileSync(join(dir, "credentials"), "{not valid");
assert.equal(heygenCredential(), null);
assert.throws(() => heygenAuthHeaders(), /can't be read \(not valid JSON\)/);
assert.deepEqual(notes, []);
});
});
}
test("a malformed credentials file refuses a received .env key and says to fix that file", () => {
withProjectEnv("hg_received", JSON.stringify({ files: [".env"] }), (dir, notes) => {
writeFileSync(join(dir, "credentials"), "{not valid");
assert.equal(heygenCredential(), null);
assert.throws(() => heygenAuthHeaders(), /can't be read \(not valid JSON\)/);
assert.deepEqual(notes, []);
});
});
test("a person's own project .env key stands in for a malformed credentials file", () => {
withProjectEnv("hg_own", undefined, (dir) => {
writeFileSync(join(dir, "credentials"), "{not valid");
assert.deepEqual(heygenCredential(), { headers: { "X-Api-Key": "hg_own" } });
});
});
test("a person's own project .env key stands in for a saved login that expired", () => {
withProjectEnv("hg_own", undefined, (dir) => {
const login = {
client_id: "Zg3LF4FCLoeJoGs2YqMtZ17g",
token_endpoint: "https://api2.heygen.com/v1/oauth/token",
access_token: "at_login",
expires_at: "2000-01-01T00:00:00Z",
};
writeFileSync(join(dir, "credentials"), JSON.stringify({ oauth: login }));
assert.deepEqual(heygenCredential(), { headers: { "X-Api-Key": "hg_own" } });
});
});
test("heygenAuthMethod returns api_key for an env API key, without tagging headers", () => {
withCleanHeygenEnv(() => {
process.env.HEYGEN_API_KEY = "hg_test";
+1 -1
View File
@@ -4,7 +4,7 @@
## Signing in
`npx hyperframes auth status` says what is signed in. The credential is read in this order: a host app's `HEYGEN_ACCESS_TOKEN`, the session `npx hyperframes auth login` saved in `~/.hyperframes/credentials`, `HEYGEN_API_KEY`, `HYPERFRAMES_API_KEY`, then an API key saved with `auth login --api-key`. A key that a received project's `.env` sets is used only when no login or key is saved, never in place of an expired session. A signed-in session wins over an env key; the env key is used when HeyGen refuses to refresh the session. `heygen auth login` is a separate sign-in that only the `heygen` CLI reads.
`npx hyperframes auth status` says what is signed in. The credential is read in this order: a host app's `HEYGEN_ACCESS_TOKEN`, the session `npx hyperframes auth login` saved in `~/.hyperframes/credentials`, `HEYGEN_API_KEY`, `HYPERFRAMES_API_KEY` set in the shell, an API key saved with `auth login --api-key`, then a key that a project's `.env` sets. A project `.env` key is used only when no login or key is saved and the shell sets none, never in place of an expired session, and the scripts name that `.env` file on stderr when they use one. A signed-in session wins over an env key; the env key is used when HeyGen refuses to refresh the session. `heygen auth login` is a separate sign-in that only the `heygen` CLI reads.
| Credential | Pays with | Covers |
| -------------------------- | -------------------------------------------- | -------------------------------------------------------------------------------------- |