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
+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).