Skip to content

Write HTML. Render video. Built for agents.

fix(cli): publish with a refused login refreshes or asks you to log in again (#4964)

Miguel Ángelde9bf487d421
diff --git a/packages/cli/src/auth/errors.ts b/packages/cli/src/auth/errors.ts
index dbf4893168..bb307c9d3c 100644
--- a/packages/cli/src/auth/errors.ts
+++ b/packages/cli/src/auth/errors.ts
@@ -10,7 +10,9 @@ export type AuthErrorCode =
| "UNAUTHENTICATED"
| "OAUTH_NOT_CONFIGURED"
| "DEVICE_AUTH_FAILED"
- | "REFRESH_FAILED";
+ | "REFRESH_FAILED"
+ | "LOGIN_EXPIRED"
+ | "LOGIN_CHANGED";
export class AuthError extends Error {
readonly code: AuthErrorCode;
@@ -62,6 +64,20 @@ export const ErrRefreshFailed = (detail?: string) =>
"Run `hyperframes auth login` to re-authenticate.",
);
+export const ErrLoginExpired = () =>
+ new AuthError(
+ "LOGIN_EXPIRED",
+ "Your HeyGen login expired",
+ "Run `hyperframes auth login` to sign in again.",
+ );
+
+export const ErrLoginChanged = () =>
+ new AuthError(
+ "LOGIN_CHANGED",
+ "Your HeyGen login changed while this command ran",
+ "Run the command again.",
+ );
+
export const ErrDeviceAuthFailed = (detail: string) =>
new AuthError(
"DEVICE_AUTH_FAILED",
diff --git a/packages/cli/src/auth/oauth.test.ts b/packages/cli/src/auth/oauth.test.ts
index fcc9ac5150..a391ef7f7d 100644
--- a/packages/cli/src/auth/oauth.test.ts
+++ b/packages/cli/src/auth/oauth.test.ts
@@ -172,6 +172,7 @@ describe("auth/oauth", () => {
describe("refreshTokens", () => {
it("posts grant_type=refresh_token and persists the response", async () => {
process.env["HEYGEN_API_URL"] = "https://api.test.example";
+ await writeStore({ oauth: { access_token: "old_at", refresh_token: "old_rt" } });
let capturedBody: string | undefined;
const fetchImpl = (async (_url: string, init?: RequestInit) => {
capturedBody = init?.body as string;
@@ -214,8 +215,36 @@ describe("auth/oauth", () => {
expect(credentials.oauth?.refresh_token).toBe("keep_me_rt");
});
+ it("leaves a login that replaced the refreshed one untouched", async () => {
+ const login = {
+ oauth: { access_token: "b_at", refresh_token: "b_rt" },
+ user: { email: "[email protected]" },
+ };
+ await writeStore(login);
+ const fetchImpl = tokenFetch({ access_token: "a_new_at", expires_in: 3600 });
+ await expect(refreshTokens("a_rt", { fetchImpl })).rejects.toSatisfy(
+ (err) => isAuthError(err) && err.code === "LOGIN_CHANGED",
+ );
+ const { credentials } = await readStore();
+ expect(credentials.oauth).toMatchObject(login.oauth);
+ expect(credentials.user?.email).toBe("[email protected]");
+ });
+
+ it("reports an unreadable credentials file on refresh instead of a changed login", async () => {
+ const path = (await import("./paths.js")).credentialPath();
+ await fs.writeFile(path, "{not json", { mode: 0o600 });
+ const fetchImpl = tokenFetch({ access_token: "new_at", expires_in: 3600 });
+ await expect(refreshTokens("old_rt", { fetchImpl })).rejects.toSatisfy(
+ (err) => isAuthError(err) && err.code === "INVALID_STORE",
+ );
+ expect(await fs.readFile(path, "utf8")).toBe("{not json");
+ });
+
it("preserves an existing api_key when persisting refreshed oauth", async () => {
- await writeStore({ api_key: "hg_keep" });
+ await writeStore({
+ api_key: "hg_keep",
+ oauth: { access_token: "old_at", refresh_token: "old_rt" },
+ });
const fetchImpl = tokenFetch({ access_token: "new_at", expires_in: 60 });
await refreshTokens("old_rt", { fetchImpl });
const { credentials } = await readStore();
@@ -224,7 +253,7 @@ describe("auth/oauth", () => {
});
it("preserves an unknown key INSIDE the oauth sub-object across a refresh", async () => {
- // The refresh path is `persistOAuth(preserveMissing: true)`, i.e.
+ // The refresh path is `persistOAuth({ refreshed })`, i.e.
// `{ ...existing.oauth, ...tokens }` — object spread carries the
// hidden Symbol-keyed unknown bag from `existing.oauth`, so a key
// another CLI wrote inside `oauth` (e.g. an `id_token`) must survive
diff --git a/packages/cli/src/auth/oauth.ts b/packages/cli/src/auth/oauth.ts
index a1c0a20476..4ef646beb8 100644
--- a/packages/cli/src/auth/oauth.ts
+++ b/packages/cli/src/auth/oauth.ts
@@ -37,6 +37,7 @@ import { failCommand } from "../utils/commandResult.js";
import {
ErrApi,
ErrDeviceAuthFailed,
+ ErrLoginChanged,
ErrOAuthNotConfigured,
ErrRefreshFailed,
isAuthError,
@@ -205,7 +206,7 @@ export async function startAuthorizationCodeFlow(
});
// Fresh login → clean OAuth block (no inherited refresh_token).
- await persistOAuth(tokens, { preserveMissing: false });
+ await persistOAuth(tokens);
return { tokens };
}
@@ -411,7 +412,7 @@ export async function refreshTokens(
const payload = await readJsonOrThrow(res);
const tokens = parseTokenResponse(payload);
// Refresh grant → preserve a refresh_token the server didn't rotate.
- await persistOAuth(tokens, { preserveMissing: true });
+ await persistOAuth(tokens, { refreshed: refresh_token });
return tokens;
}
@@ -592,38 +593,36 @@ function numericField(obj: Record<string, unknown>, key: string): number | undef
}
/**
- * Persist a new OAuth token set, always preserving a co-located
- * `api_key`.
+ * Persist a new OAuth token set, always preserving a co-located `api_key`.
*
- * `preserveMissing` controls how the new tokens combine with whatever
- * OAuth block is already on disk:
- * - `false` (fresh authorization-code login): overwrite the OAuth
+ * `refreshed` (the refresh_token that was exchanged) controls how the new
+ * tokens combine with whatever OAuth block is already on disk:
+ * - absent (fresh authorization-code login): overwrite the OAuth
* block entirely. A new interactive login is a clean session — it
* must NOT inherit the previous session's refresh_token, or a
* response that omits one would pair a new access token with a
* stale refresh token and break/misroute the next refresh.
- * - `true` (refresh grant): keep the prior refresh_token / scope /
+ * - set (refresh grant): keep the prior refresh_token / scope /
* token_type when the response omits them. RFC 6749 §6 lets the
* token endpoint skip refresh_token on a no-rotation refresh, and
- * dropping it would brick future refreshes.
+ * dropping it would brick future refreshes. Throws `LOGIN_CHANGED`
+ * without writing if the stored login is no longer the refreshed one.
*/
-async function persistOAuth(
- tokens: OAuthTokens,
- opts: { preserveMissing: boolean },
-): Promise<void> {
+async function persistOAuth(tokens: OAuthTokens, opts: { refreshed?: string } = {}): Promise<void> {
let existing: Credentials = {};
try {
const { credentials } = await readStore();
existing = credentials;
- } catch {
- // Treat unreadable existing file as empty — we're about to
- // overwrite the OAuth block anyway.
- existing = {};
+ } catch (err) {
+ // A fresh login overwrites the OAuth block anyway; a refresh must not guess.
+ if (opts.refreshed !== undefined) throw err;
}
- const oauth: OAuthTokens = opts.preserveMissing
- ? { ...existing.oauth, ...tokens }
- : { ...tokens };
+ if (opts.refreshed !== undefined && existing.oauth?.refresh_token !== opts.refreshed) {
+ throw ErrLoginChanged();
+ }
+ const oauth: OAuthTokens =
+ opts.refreshed !== undefined ? { ...existing.oauth, ...tokens } : { ...tokens };
// Start from the existing record so co-located data survives: the
// api_key, the friendly-display `user` block, AND any unknown/foreign
// keys another CLI wrote (carried on a hidden symbol slot by spread).
@@ -633,7 +632,7 @@ async function persistOAuth(
/** Persist a verified fresh OAuth login while preserving cross-CLI fields. */
export async function persistFreshOAuth(tokens: OAuthTokens): Promise<void> {
- await persistOAuth(tokens, { preserveMissing: false });
+ await persistOAuth(tokens);
}
/**
diff --git a/packages/cli/src/auth/resolver.test.ts b/packages/cli/src/auth/resolver.test.ts
index ad10ade1c1..b69a40799f 100644
--- a/packages/cli/src/auth/resolver.test.ts
+++ b/packages/cli/src/auth/resolver.test.ts
@@ -89,6 +89,14 @@ describe("auth/resolver", () => {
if (r.type === "api_key") expect(r.key).toBe("fallback");
});
+ it("reports an expired login with no refresh token as expired, not as never signed in", async () => {
+ const past = new Date(Date.now() - 60 * 60 * 1000).toISOString();
+ await writeStore({ oauth: { access_token: "stale-at", expires_at: past } });
+ await expect(tryResolveCredential()).rejects.toSatisfy((err) => {
+ return isAuthError(err) && (err as { code: string }).code === "LOGIN_EXPIRED";
+ });
+ });
+
it("rejects HEYGEN_API_KEY containing CRLF (header-injection guard)", async () => {
process.env["HEYGEN_API_KEY"] = "hg_x\r\nX-Evil: 1";
await expect(resolveCredential()).rejects.toSatisfy((err) => {
diff --git a/packages/cli/src/auth/resolver.ts b/packages/cli/src/auth/resolver.ts
index 6b0ca0f118..404959621a 100644
--- a/packages/cli/src/auth/resolver.ts
+++ b/packages/cli/src/auth/resolver.ts
@@ -13,11 +13,11 @@
* Expiry policy: an OAuth access_token whose `expires_at` is in the
* past (60s skew) is considered expired. If a `refresh_token` is also
* present, callers can still use it via `refreshable: true`. Otherwise
- * the api_key (if any) wins.
+ * the api_key (if any) wins, else `ErrLoginExpired`, not `ErrNotConfigured`.
*/
import { isHeaderSafe, readStore } from "./store.js";
-import { ErrInvalidStore, ErrNotConfigured, isAuthError } from "./errors.js";
+import { ErrInvalidStore, ErrLoginExpired, ErrNotConfigured, isAuthError } from "./errors.js";
type CredentialSource = "env" | "env_alias" | "file_json" | "file_legacy";
@@ -70,14 +70,12 @@ export async function resolveCredential(opts: ResolveOptions = {}): Promise<Reso
const fileSource: CredentialSource = source === "file_legacy" ? "file_legacy" : "file_json";
- if (credentials.oauth) {
- const oauth = pickOAuth(credentials.oauth, now, fileSource);
- if (oauth) return oauth;
- }
+ const oauth = credentials.oauth ? pickOAuth(credentials.oauth, now, fileSource) : null;
+ if (oauth) return oauth;
if (credentials.api_key) {
return { type: "api_key", key: credentials.api_key, source: fileSource };
}
- throw ErrNotConfigured();
+ throw credentials.oauth ? ErrLoginExpired() : ErrNotConfigured();
}
/** Like `resolveCredential` but returns `null` instead of throwing `NOT_CONFIGURED`. */
@@ -100,7 +98,7 @@ function pickOAuth(
source: CredentialSource,
): OAuthCredential | null {
const expiresAt = parseDate(tokens.expires_at);
- const expired = expiresAt !== undefined && expiresAt.getTime() - EXPIRY_SKEW_MS < now.getTime();
+ const expired = isTokenExpired(expiresAt, now);
if (expired && !tokens.refresh_token) return null;
@@ -116,6 +114,10 @@ function pickOAuth(
return out;
}
+export function isTokenExpired(expiresAt: Date | undefined, now: Date): boolean {
+ return expiresAt !== undefined && expiresAt.getTime() - EXPIRY_SKEW_MS < now.getTime();
+}
+
function parseDate(s: string | undefined): Date | undefined {
if (!s) return undefined;
const d = new Date(s);
diff --git a/packages/cli/src/cloud/auth.ts b/packages/cli/src/cloud/auth.ts
index 18c8f8e230..26238d37af 100644
--- a/packages/cli/src/cloud/auth.ts
+++ b/packages/cli/src/cloud/auth.ts
@@ -39,7 +39,7 @@ export function resolveCloudBaseUrl(): string {
}
// fallow-ignore-next-line complexity
-async function refreshIfNeeded(credential: ResolvedCredential): Promise<ResolvedCredential> {
+export async function refreshIfNeeded(credential: ResolvedCredential): Promise<ResolvedCredential> {
if (credential.type !== "oauth") return credential;
if (!credential.refreshable || !credential.refresh_token) return credential;
const fresh = await refreshTokens(credential.refresh_token);
diff --git a/packages/cli/src/commands/publish.test.ts b/packages/cli/src/commands/publish.test.ts
index c8eb1d5e6e..552c4272fa 100644
--- a/packages/cli/src/commands/publish.test.ts
+++ b/packages/cli/src/commands/publish.test.ts
@@ -12,6 +12,28 @@ vi.mock("../utils/publishProject.js", async (importOriginal) => ({
import publishCommand, { examples, parseUpdateTarget } from "./publish.js";
import { ensureProjectId } from "../utils/projectLink.js";
+import { writeStore } from "../auth/store.js";
+import { consumeCommandResult } from "../utils/commandResult.js";
+
+const VISIBLE_INDEX = `<html><body><div data-composition-id="main" data-width="1920" data-height="1080" data-start="0" data-duration="5"><div class="clip" data-start="0" data-duration="5">Visible</div></div></body></html>`;
+
+function mockPublished(result: Record<string, unknown>): void {
+ publishState.publish.mockReset();
+ publishState.publish.mockResolvedValue({ title: "test", fileCount: 1, claimed: true, ...result });
+}
+
+async function captureLog(run: () => Promise<unknown>): Promise<string> {
+ const lines: string[] = [];
+ const log = vi.spyOn(console, "log").mockImplementation((...parts: unknown[]) => {
+ lines.push(parts.map(String).join(" "));
+ });
+ try {
+ await run();
+ } finally {
+ log.mockRestore();
+ }
+ return lines.join("\n");
+}
describe("parseUpdateTarget", () => {
it("extracts the id from a full published URL", () => {
@@ -50,28 +72,17 @@ describe("publish default-entry preflight", () => {
candidatePath,
`<html><body><div data-composition-id="authored" data-width="1920" data-height="1080" data-start="0" data-duration="5"><div class="clip" data-start="0" data-duration="5">Visible</div></div></body></html>`,
);
- publishState.publish.mockReset();
- publishState.publish.mockResolvedValue({
- title: "test",
- fileCount: 2,
- claimed: true,
- projectId: "project-id",
- url: "https://hyperframes.dev/p/project-id",
- claimToken: "",
- });
- const lines: string[] = [];
- const log = vi.spyOn(console, "log").mockImplementation((...parts: unknown[]) => {
- lines.push(parts.map(String).join(" "));
- });
+ mockPublished({ projectId: "project-id", url: "https://hyperframes.dev/p/project-id" });
try {
- await expect(
- publishCommand.run?.({ args: { dir: project, yes: true, proxy: false } } as never),
- ).rejects.toMatchObject({ name: "CliRuntimeError" });
+ const output = await captureLog(() =>
+ expect(
+ publishCommand.run?.({ args: { dir: project, yes: true, proxy: false } } as never),
+ ).rejects.toMatchObject({ name: "CliRuntimeError" }),
+ );
expect(publishState.publish).not.toHaveBeenCalled();
- return lines.join("\n");
+ return output;
} finally {
- log.mockRestore();
rmSync(project, { recursive: true, force: true });
}
}
@@ -106,34 +117,24 @@ describe("publish visibility messaging", () => {
inPlace?: boolean;
}): Promise<string> {
const project = mkdtempSync(join(tmpdir(), "hf-publish-visibility-"));
- writeFileSync(
- join(project, "index.html"),
- `<html><body><div data-composition-id="main" data-width="1920" data-height="1080" data-start="0" data-duration="5"><div class="clip" data-start="0" data-duration="5">Visible</div></div></body></html>`,
- );
+ writeFileSync(join(project, "index.html"), VISIBLE_INDEX);
// "Updated in place" is decided by the response echoing the id the directory already
// resolves to — no --update flag required, which is how a plain re-publish reaches it.
const projectId = options.inPlace === true ? ensureProjectId(project) : "project-id";
- publishState.publish.mockReset();
- publishState.publish.mockResolvedValue({
- title: "test",
- fileCount: 1,
+ mockPublished({
claimed: options.claimed ?? true,
projectId,
url: `https://hyperframes.dev/p/${projectId}`,
claimToken: "claim-secret",
});
- const lines: string[] = [];
- const log = vi.spyOn(console, "log").mockImplementation((...parts: unknown[]) => {
- lines.push(parts.map(String).join(" "));
- });
try {
- await publishCommand.run?.({
- args: { dir: project, yes: true, public: options.public, proxy: false },
- } as never);
- return lines.join("\n");
+ return await captureLog(() =>
+ publishCommand.run?.({
+ args: { dir: project, yes: true, public: options.public, proxy: false },
+ } as never),
+ );
} finally {
- log.mockRestore();
rmSync(project, { recursive: true, force: true });
}
}
@@ -182,3 +183,180 @@ describe("publish visibility messaging", () => {
expect(examples[0]?.[0]).not.toContain("public URL");
});
});
+
+describe("publish --update / --space ownership preflight", () => {
+ async function runWithFlag(
+ flag: { update?: string; space?: string },
+ credentials: { env?: string; stored?: Parameters<typeof writeStore>[0] },
+ publish?: (...args: unknown[]) => Promise<unknown>,
+ ): Promise<{ output: string; exitCode: number }> {
+ const project = mkdtempSync(join(tmpdir(), "hf-publish-owner-"));
+ const config = mkdtempSync(join(tmpdir(), "hf-publish-owner-config-"));
+ writeFileSync(join(project, "index.html"), VISIBLE_INDEX);
+ vi.stubEnv("HEYGEN_CONFIG_DIR", config);
+ vi.stubEnv("HEYGEN_API_KEY", credentials.env ?? "");
+ vi.stubEnv("HYPERFRAMES_API_KEY", "");
+ if (credentials.stored) await writeStore(credentials.stored, join(config, "credentials"));
+ mockPublished({ projectId: "target", url: "https://hyperframes.dev/p/target" });
+ if (publish) publishState.publish.mockImplementation(publish);
+ try {
+ consumeCommandResult();
+ const output = await captureLog(() =>
+ publishCommand.run?.({
+ args: { dir: project, yes: true, public: false, proxy: false, ...flag },
+ } as never),
+ );
+ return { output, exitCode: consumeCommandResult().exitCode };
+ } finally {
+ vi.unstubAllEnvs();
+ vi.unstubAllGlobals();
+ rmSync(project, { recursive: true, force: true });
+ rmSync(config, { recursive: true, force: true });
+ }
+ }
+
+ it.each([
+ { flag: { update: "target" }, name: "--update" },
+ { flag: { space: "space-1" }, name: "--space" },
+ ])("refuses $name with an env API key before uploading", async ({ flag, name }) => {
+ const { output, exitCode } = await runWithFlag(flag, { env: "valid-key" });
+
+ expect(publishState.publish).not.toHaveBeenCalled();
+ expect(exitCode).toBe(1);
+ expect(output).toContain(`${name} requires a login; HEYGEN_API_KEY cannot own a project`);
+ });
+
+ it("refuses --update with a saved API key before uploading", async () => {
+ const { output, exitCode } = await runWithFlag(
+ { update: "target" },
+ { stored: { api_key: "valid-key" } },
+ );
+
+ expect(publishState.publish).not.toHaveBeenCalled();
+ expect(exitCode).toBe(1);
+ expect(output).toContain("--update requires a login; an API key cannot own a project");
+ });
+
+ it("publishes --update with a login", async () => {
+ const { output, exitCode } = await runWithFlag(
+ { update: "target" },
+ { stored: { oauth: { access_token: "token" } } },
+ );
+
+ expect(publishState.publish).toHaveBeenCalledWith(
+ expect.any(String),
+ expect.objectContaining({ projectId: "target" }),
+ );
+ expect(exitCode).toBe(0);
+ expect(output).toContain("Updated existing project");
+ });
+
+ // The login expires while proxies bake; a second credential lookup at upload time would
+ // fall back to the saved API key, publish unowned and drop the flag without a word.
+ it.each([{ update: "target" }, { space: "space-1" }])(
+ "uploads with the checked login even if it expires mid-publish (%o)",
+ async (flag) => {
+ const { publishProjectArchive } = await vi.importActual<
+ typeof import("../utils/publishProject.js")
+ >("../utils/publishProject.js");
+ const fetchMock = vi.fn(async (url: string) =>
+ url.endsWith("/publish/upload")
+ ? new Response(null, { status: 404 })
+ : Response.json({
+ data: {
+ project_id: "anon",
+ title: "test",
+ url: "https://hyperframes.dev/p/anon",
+ file_count: 1,
+ claimed: false,
+ claim_token: "claim-secret",
+ },
+ }),
+ );
+ vi.stubGlobal("fetch", fetchMock);
+ const past = new Date(Date.now() - 60 * 60 * 1000).toISOString();
+
+ const { output, exitCode } = await runWithFlag(
+ flag,
+ { stored: { oauth: { access_token: "token" }, api_key: "valid-key" } },
+ async (dir, opts) => {
+ await writeStore({
+ oauth: { access_token: "token", expires_at: past },
+ api_key: "valid-key",
+ });
+ return publishProjectArchive(dir as string, opts as never);
+ },
+ );
+
+ for (const [, init] of fetchMock.mock.calls as unknown as [string, RequestInit][]) {
+ expect(init.headers).toMatchObject({ authorization: "Bearer token" });
+ expect(init.headers).not.toHaveProperty("x-api-key");
+ }
+ expect(fetchMock).toHaveBeenCalled();
+ expect(exitCode).toBe(1);
+ expect(output).not.toContain("Claim URL");
+ },
+ );
+
+ // Another CLI logs in as B while A's publish bakes; refreshing A must not write over B.
+ it("fails without touching a login that replaced the checked one mid-publish", async () => {
+ const { publishProjectArchive } = await vi.importActual<
+ typeof import("../utils/publishProject.js")
+ >("../utils/publishProject.js");
+ const { readStore } = await import("../auth/store.js");
+ vi.stubEnv("HYPERFRAMES_OAUTH_TOKEN_URL", "https://auth.test/token");
+ const fetchMock = vi.fn(async (url: string) =>
+ url === "https://auth.test/token"
+ ? Response.json({ access_token: "a-new", expires_in: 3600 })
+ : Response.json({
+ data: {
+ project_id: "target",
+ title: "test",
+ url: "https://hyperframes.dev/p/target",
+ file_count: 1,
+ claimed: true,
+ },
+ }),
+ );
+ vi.stubGlobal("fetch", fetchMock);
+ const loginB = { access_token: "b-token", refresh_token: "b-refresh" };
+ const errors: string[] = [];
+ const error = vi.spyOn(console, "error").mockImplementation((...parts: unknown[]) => {
+ errors.push(parts.map(String).join(" "));
+ });
+ let stored: Awaited<ReturnType<typeof readStore>> | undefined;
+ try {
+ const { exitCode } = await runWithFlag(
+ { update: "target" },
+ {
+ stored: {
+ oauth: {
+ access_token: "a-token",
+ refresh_token: "a-refresh",
+ expires_at: new Date(Date.now() + 90_000).toISOString(),
+ },
+ },
+ },
+ async (dir, opts) => {
+ await writeStore({ oauth: loginB, user: { email: "[email protected]" } });
+ vi.useFakeTimers({ toFake: ["Date"] });
+ vi.setSystemTime(Date.now() + 10 * 60_000);
+ try {
+ return await publishProjectArchive(dir as string, opts as never);
+ } finally {
+ stored = await readStore();
+ vi.useRealTimers();
+ }
+ },
+ );
+
+ expect(stored?.credentials.oauth).toMatchObject(loginB);
+ expect(stored?.credentials.user?.email).toBe("[email protected]");
+ expect(fetchMock.mock.calls.map(([url]) => url)).toEqual(["https://auth.test/token"]);
+ expect(exitCode).toBe(1);
+ expect(errors.join("\n")).toContain("Your login changed during publish. Run publish again.");
+ } finally {
+ error.mockRestore();
+ }
+ });
+});
diff --git a/packages/cli/src/commands/publish.ts b/packages/cli/src/commands/publish.ts
index 8a18116f5d..70810019ea 100644
--- a/packages/cli/src/commands/publish.ts
+++ b/packages/cli/src/commands/publish.ts
@@ -13,13 +13,15 @@ import {
} from "../utils/lintProject.js";
import { formatLintStartupMessage } from "../utils/lintFormat.js";
import {
+ API_KEY_ENV_VAR,
buildPublishFileMap,
publishProjectArchive,
+ resolvePublishCredential,
zipPublishFileMap,
} from "../utils/publishProject.js";
import { bakeMediaProxies } from "../utils/publishProxyBake.js";
+import type { ResolvedCredential } from "../auth/resolver.js";
import { resolveAutoProxy } from "../utils/projectConfig.js";
-import { tryResolveCredential } from "../auth/index.js";
import {
ensureProjectId,
readProjectLink,
@@ -163,14 +165,37 @@ export default defineCommand({
const spaceOverride =
typeof args.space === "string" && args.space.trim() ? args.space.trim() : undefined;
- // --update / --space only take effect for an authenticated owner. Fail loudly rather
- // than silently minting a fresh URL — the exact failure mode this feature removes.
+ // Resolved once and passed to the upload: a second lookup after the bake could fall back
+ // from an expired login to a saved API key and silently drop --update / --space.
+ let credential: ResolvedCredential | null;
+ try {
+ credential = await resolvePublishCredential();
+ } catch (err: unknown) {
+ console.error();
+ console.error(` ${(err as Error).message}`);
+ console.error();
+ setCommandExitCode(1);
+ return;
+ }
+
+ // --update / --space only take effect for a login (an API-key publish is never owned).
+ // Fail loudly rather than silently minting a fresh URL.
if (updateTarget || spaceOverride) {
- const credential = await tryResolveCredential();
- if (!credential) {
+ if (credential?.type !== "oauth") {
+ const flag = updateTarget ? "--update" : "--space";
+ const envKey =
+ credential?.source === "env" || credential?.source === "env_alias"
+ ? API_KEY_ENV_VAR[credential.source]
+ : undefined;
console.log();
console.log(
- ` ${c.error(`${updateTarget ? "--update" : "--space"} requires authentication. Run 'hyperframes auth login' first.`)}`,
+ ` ${c.error(
+ !credential
+ ? `${flag} requires authentication. Run 'hyperframes auth login' first.`
+ : envKey
+ ? `${flag} requires a login; ${envKey} cannot own a project. Unset it and run 'hyperframes auth login'.`
+ : `${flag} requires a login; an API key cannot own a project. Run 'hyperframes auth login'.`,
+ )}`,
);
console.log();
setCommandExitCode(1);
@@ -215,6 +240,7 @@ export default defineCommand({
projectId: requestedProjectId,
spaceId,
archive,
+ credential,
});
publishSpinner.stop(c.success("Project published"));
@@ -289,27 +315,15 @@ export default defineCommand({
console.log(` ${c.dim("Claim URL")} ${c.accent(claimUrl.toString())}`);
console.log(` ${c.dim("Access")} ${c.accent("Sign in required to claim")}`);
console.log();
- if (updateTarget || spaceOverride) {
- // The pre-publish gate saw a credential, but the server didn't accept it (expired
- // or invalid) and fell back to anonymous — say so loudly instead of pretending the
- // requested update happened.
- console.log(
- ` ${c.error(`Your login looks expired or invalid, so ${updateTarget ? "--update" : "--space"} was ignored and a NEW url was created above.`)}`,
- );
- console.log(
- ` ${c.dim("Run 'hyperframes auth login' again, then re-publish to update in place.")}`,
- );
- } else {
- console.log(
- ` ${c.dim("Open the claim URL on hyperframes.dev, sign in, and claim the project to continue editing.")}`,
- );
- console.log();
- const visibilityTip =
- args.public === true
- ? "--public applies to the claimed project; this claim URL still requires sign-in."
- : "Run 'hyperframes auth login' first for a stable link you can re-publish to; add --public to allow signed-out viewing.";
- console.log(` ${c.dim(`Tip: ${visibilityTip}`)}`);
- }
+ console.log(
+ ` ${c.dim("Open the claim URL on hyperframes.dev, sign in, and claim the project to continue editing.")}`,
+ );
+ console.log();
+ const visibilityTip =
+ args.public === true
+ ? "--public applies to the claimed project; this claim URL still requires sign-in."
+ : "Run 'hyperframes auth login' first for a stable link you can re-publish to; add --public to allow signed-out viewing.";
+ console.log(` ${c.dim(`Tip: ${visibilityTip}`)}`);
console.log();
}
return;
diff --git a/packages/cli/src/utils/publishProject.test.ts b/packages/cli/src/utils/publishProject.test.ts
index d03a9eb174..7878c2cd38 100644
--- a/packages/cli/src/utils/publishProject.test.ts
+++ b/packages/cli/src/utils/publishProject.test.ts
@@ -20,6 +20,18 @@ vi.mock("./projectLink.js", () => ({
writeProjectLink: linkMocks.writeProjectLink,
}));
+const oauthMocks = vi.hoisted(() => ({
+ refreshTokens: vi.fn(),
+}));
+
+vi.mock("../auth/oauth.js", () => ({
+ refreshTokens: oauthMocks.refreshTokens,
+}));
+
+import { ErrRefreshFailed } from "../auth/errors.js";
+import { setupTempAuthEnv } from "../auth/_test-utils.js";
+import { writeStore } from "../auth/store.js";
+
import {
buildPublishFileMap,
createPublishArchive,
@@ -129,6 +141,9 @@ function publishedResponse(overrides?: Record<string, unknown>): Response {
);
}
+/** What the server returns when it accepted the credential and owns the project. */
+const OWNED = { claim_token: "", claimed: true };
+
/** Full staged flow: upload, S3 PUT, complete. */
function stagedFetch(completeData?: Record<string, unknown>, uploadData?: Record<string, unknown>) {
return vi
@@ -597,6 +612,7 @@ describe("uploadTimeoutMs", () => {
// nested in a describe) so the reset logic isn't duplicated per group.
beforeEach(() => {
authMocks.tryResolveCredential.mockReset().mockResolvedValue(null);
+ oauthMocks.refreshTokens.mockReset();
linkMocks.writeProjectLink.mockReset();
vi.stubEnv("HYPERFRAMES_PUBLISHED_PROJECTS_API_URL", "");
vi.stubEnv("HEYGEN_API_URL", "");
@@ -673,7 +689,7 @@ describe("publishProjectArchive", () => {
describe("publishProjectArchive", () => {
it("authenticates staged metadata requests but not the presigned S3 upload", async () => {
const dir = makeProjectDir();
- const fetchMock = stagedFetch();
+ const fetchMock = stagedFetch(OWNED);
try {
await runAuthenticatedPublish(fetchMock, dir);
@@ -689,7 +705,7 @@ describe("publishProjectArchive", () => {
it("authenticates the direct fallback request", async () => {
const dir = makeProjectDir();
- const fetchMock = directFetch();
+ const fetchMock = directFetch(OWNED);
try {
await runAuthenticatedPublish(fetchMock, dir);
@@ -986,8 +1002,7 @@ function ownedStagedFetch() {
return stagedFetch({
project_id: "hfp_stable",
url: "https://hyperframes.dev/p/hfp_stable",
- claim_token: "",
- claimed: true,
+ ...OWNED,
});
}
@@ -1020,7 +1035,7 @@ describe("publishProjectArchive", () => {
it("never sends a project id or persists a link when anonymous", async () => {
// Default credential is null (anonymous).
const dir = makeProjectDir();
- const fetchMock = ownedStagedFetch();
+ const fetchMock = stagedFetch();
vi.stubGlobal("fetch", fetchMock);
try {
@@ -1067,3 +1082,215 @@ describe("publishProjectArchive", () => {
expect(anon.mock.calls[2]![1].headers).not.toHaveProperty("x-space-id");
});
});
+
+describe("publishProjectArchive with a credential the server rejects", () => {
+ const EXPIRED = "Your login expired. Run hyperframes auth login, then publish again.";
+ const unauthorized = () =>
+ new Response(JSON.stringify({ message: "Unauthorized" }), {
+ status: 401,
+ headers: { "content-type": "application/json" },
+ });
+
+ async function publishExpecting(fetchMock: ReturnType<typeof vi.fn>, message: string) {
+ const dir = makeProjectDir();
+ try {
+ await expect(runAuthenticatedPublish(fetchMock, dir)).rejects.toThrow(message);
+ } finally {
+ rmSync(dir, { recursive: true, force: true });
+ }
+ }
+
+ it("stops at the first request, before any upload, with a re-login message", async () => {
+ const fetchMock = vi.fn().mockResolvedValueOnce(unauthorized());
+ await publishExpecting(fetchMock, EXPIRED);
+ expect(fetchMock).toHaveBeenCalledTimes(1);
+ expectAuthorizedHeaders(fetchMock, 0);
+ });
+
+ it("says the same when the final publish request is refused", async () => {
+ const fetchMock = vi
+ .fn()
+ .mockResolvedValueOnce(uploadResponse())
+ .mockResolvedValueOnce(new Response(null, { status: 200 }))
+ .mockResolvedValueOnce(unauthorized());
+ await publishExpecting(fetchMock, EXPIRED);
+ });
+
+ it("says the same on the legacy multipart publish", async () => {
+ const fetchMock = vi
+ .fn()
+ .mockResolvedValueOnce(new Response("not found", { status: 404 }))
+ .mockResolvedValueOnce(unauthorized());
+ await publishExpecting(fetchMock, EXPIRED);
+ });
+
+ it("does not blame the login for a 401 from the storage upload, which carries no credential", async () => {
+ const fetchMock = vi
+ .fn()
+ .mockResolvedValueOnce(uploadResponse())
+ .mockResolvedValueOnce(new Response("denied", { status: 401 }));
+ await publishExpecting(fetchMock, "Failed to upload project archive");
+ });
+
+ it("refuses an anonymous result for a signed-in publish and links nothing", async () => {
+ await publishExpecting(stagedFetch(), EXPIRED);
+ await publishExpecting(directFetch(), EXPIRED);
+ expect(linkMocks.writeProjectLink).not.toHaveBeenCalled();
+ });
+
+ it("publishes with an API key, which the server never marks as owned, and links nothing", async () => {
+ const dir = makeProjectDir();
+ try {
+ authMocks.tryResolveCredential.mockResolvedValue({
+ type: "api_key",
+ key: "k",
+ source: "env",
+ });
+ vi.stubGlobal("fetch", stagedFetch());
+ writeFileSync(join(dir, "index.html"), "<html></html>", "utf-8");
+ const result = await publishProjectArchive(dir);
+ expect(result.claimToken).toBe("claim-token");
+ expect(linkMocks.writeProjectLink).not.toHaveBeenCalled();
+ } finally {
+ rmSync(dir, { recursive: true, force: true });
+ }
+ });
+
+ it("names the environment API key instead of asking for a login it would not use", async () => {
+ const fetchMock = vi.fn().mockResolvedValueOnce(unauthorized());
+ const dir = makeProjectDir();
+ try {
+ authMocks.tryResolveCredential.mockResolvedValue({
+ type: "api_key",
+ key: "k",
+ source: "env",
+ });
+ vi.stubGlobal("fetch", fetchMock);
+ writeFileSync(join(dir, "index.html"), "<html></html>", "utf-8");
+ await expect(publishProjectArchive(dir)).rejects.toThrow(
+ "HEYGEN_API_KEY was rejected. Fix or unset it, then publish again.",
+ );
+ } finally {
+ rmSync(dir, { recursive: true, force: true });
+ }
+ });
+});
+
+describe("publishProjectArchive with an expired login it can refresh", () => {
+ const expiredLogin = {
+ type: "oauth",
+ access_token: "stale-token",
+ refresh_token: "refresh-token",
+ source: "file_json",
+ refreshable: true,
+ };
+
+ it("refreshes the login and publishes with the new token", async () => {
+ oauthMocks.refreshTokens.mockResolvedValueOnce({ access_token: "fresh-token" });
+ authMocks.tryResolveCredential.mockResolvedValue(expiredLogin);
+ const fetchMock = stagedFetch(OWNED);
+ vi.stubGlobal("fetch", fetchMock);
+ const dir = makeProjectDir();
+ try {
+ writeFileSync(join(dir, "index.html"), "<html></html>", "utf-8");
+ await publishProjectArchive(dir);
+ expect(oauthMocks.refreshTokens).toHaveBeenCalledWith("refresh-token");
+ expect(fetchMock.mock.calls[0]![1].headers).toEqual(
+ expect.objectContaining({ authorization: "Bearer fresh-token" }),
+ );
+ } finally {
+ rmSync(dir, { recursive: true, force: true });
+ }
+ });
+
+ // The command checks the login before a proxy bake that can outlast it.
+ it("refreshes a passed login that expired since it was checked, without resolving again", async () => {
+ oauthMocks.refreshTokens.mockResolvedValueOnce({ access_token: "fresh-token" });
+ const fetchMock = stagedFetch(OWNED);
+ vi.stubGlobal("fetch", fetchMock);
+ const dir = makeProjectDir();
+ try {
+ writeFileSync(join(dir, "index.html"), "<html></html>", "utf-8");
+ await publishProjectArchive(dir, {
+ credential: {
+ ...expiredLogin,
+ expires_at: new Date(Date.now() - 1000),
+ refreshable: false,
+ },
+ } as never);
+ expect(authMocks.tryResolveCredential).not.toHaveBeenCalled();
+ expect(fetchMock.mock.calls[0]![1].headers).toEqual(
+ expect.objectContaining({ authorization: "Bearer fresh-token" }),
+ );
+ } finally {
+ rmSync(dir, { recursive: true, force: true });
+ }
+ });
+
+ it("asks for a new login, without sending anything, when a passed login expired and cannot refresh", async () => {
+ const fetchMock = vi.fn();
+ vi.stubGlobal("fetch", fetchMock);
+ const { refresh_token: _none, ...noRefresh } = expiredLogin;
+ const dir = makeProjectDir();
+ try {
+ writeFileSync(join(dir, "index.html"), "<html></html>", "utf-8");
+ await expect(
+ publishProjectArchive(dir, {
+ credential: { ...noRefresh, expires_at: new Date(Date.now() - 1000), refreshable: false },
+ } as never),
+ ).rejects.toThrow("Your login expired. Run hyperframes auth login, then publish again.");
+ expect(fetchMock).not.toHaveBeenCalled();
+ } finally {
+ rmSync(dir, { recursive: true, force: true });
+ }
+ });
+
+ it("asks for a new login, without sending anything, when the refresh is refused", async () => {
+ oauthMocks.refreshTokens.mockRejectedValueOnce(ErrRefreshFailed("invalid_grant"));
+ authMocks.tryResolveCredential.mockResolvedValue(expiredLogin);
+ const fetchMock = vi.fn();
+ vi.stubGlobal("fetch", fetchMock);
+ const dir = makeProjectDir();
+ try {
+ writeFileSync(join(dir, "index.html"), "<html></html>", "utf-8");
+ await expect(publishProjectArchive(dir)).rejects.toThrow(
+ "Your login expired. Run hyperframes auth login, then publish again.",
+ );
+ expect(fetchMock).not.toHaveBeenCalled();
+ } finally {
+ rmSync(dir, { recursive: true, force: true });
+ }
+ });
+});
+
+describe("publishProjectArchive with an expired login and no refresh token", () => {
+ let fixture: Awaited<ReturnType<typeof setupTempAuthEnv>>;
+
+ beforeEach(async () => {
+ fixture = await setupTempAuthEnv("hf-publish-expired-");
+ const { tryResolveCredential } =
+ await vi.importActual<typeof import("../auth/resolver.js")>("../auth/resolver.js");
+ authMocks.tryResolveCredential.mockImplementation(tryResolveCredential);
+ });
+
+ afterEach(async () => {
+ await fixture.restore();
+ });
+
+ it("asks for a new login instead of publishing anonymously", async () => {
+ const past = new Date(Date.now() - 60 * 60 * 1000).toISOString();
+ await writeStore({ oauth: { access_token: "stale-token", expires_at: past } });
+ const fetchMock = vi.fn();
+ vi.stubGlobal("fetch", fetchMock);
+ const dir = makeProjectDir();
+ try {
+ writeFileSync(join(dir, "index.html"), "<html></html>", "utf-8");
+ await expect(publishProjectArchive(dir)).rejects.toThrow(
+ "Your login expired. Run hyperframes auth login, then publish again.",
+ );
+ expect(fetchMock).not.toHaveBeenCalled();
+ } finally {
+ rmSync(dir, { recursive: true, force: true });
+ }
+ });
+});
diff --git a/packages/cli/src/utils/publishProject.ts b/packages/cli/src/utils/publishProject.ts
index 356b2a02df..8fd705a020 100644
--- a/packages/cli/src/utils/publishProject.ts
+++ b/packages/cli/src/utils/publishProject.ts
@@ -6,6 +6,9 @@ import ignore, { type Ignore } from "ignore";
import { CSS_URL_RE, isNonRelativeUrl, isPathInside } from "@hyperframes/core";
import { buildAuthHeaders } from "../auth/client.js";
import { tryResolveCredential } from "../auth/index.js";
+import { isAuthError } from "../auth/errors.js";
+import { isTokenExpired, type ResolvedCredential } from "../auth/resolver.js";
+import { refreshIfNeeded } from "../cloud/auth.js";
import { writeProjectLink } from "./projectLink.js";
const IGNORED_DIRS = new Set([".git", "node_modules", "dist", ".next", "coverage"]);
@@ -155,6 +158,48 @@ async function readJson(response: Response): Promise<unknown> {
.catch(() => null);
}
+class CredentialRejectedError extends Error {}
+
+async function metadataRequestError(response: Response, fallback: string): Promise<Error> {
+ const message = await readErrorMessage(response, fallback);
+ return response.status === 401 ? new CredentialRejectedError(message) : new Error(message);
+}
+
+const LOGIN_EXPIRED = "Your login expired. Run hyperframes auth login, then publish again.";
+const LOGIN_CHANGED = "Your login changed during publish. Run publish again.";
+export const API_KEY_ENV_VAR = { env: "HEYGEN_API_KEY", env_alias: "HYPERFRAMES_API_KEY" } as const;
+
+function rejectedCredentialMessage(credential: ResolvedCredential): string {
+ if (
+ credential.type === "api_key" &&
+ (credential.source === "env" || credential.source === "env_alias")
+ ) {
+ return `${API_KEY_ENV_VAR[credential.source]} was rejected. Fix or unset it, then publish again.`;
+ }
+ return LOGIN_EXPIRED;
+}
+
+/** Resolves the credential, or refreshes `checked` (a credential already resolved) without re-resolving. */
+export async function resolvePublishCredential(
+ checked?: ResolvedCredential | null,
+): Promise<ResolvedCredential | null> {
+ try {
+ const credential = checked === undefined ? await tryResolveCredential() : checked;
+ if (!credential) return null;
+ // A checked login can expire during a long proxy bake; refresh it rather than fall back to an API key.
+ const expired =
+ credential.type === "oauth" && isTokenExpired(credential.expires_at, new Date());
+ if (expired && !credential.refresh_token) throw new Error(LOGIN_EXPIRED);
+ return await refreshIfNeeded(expired ? { ...credential, refreshable: true } : credential);
+ } catch (error) {
+ if (isAuthError(error) && (error.code === "REFRESH_FAILED" || error.code === "LOGIN_EXPIRED")) {
+ throw new Error(LOGIN_EXPIRED);
+ }
+ if (isAuthError(error) && error.code === "LOGIN_CHANGED") throw new Error(LOGIN_CHANGED);
+ throw error;
+ }
+}
+
async function readErrorMessage(response: Response, fallback: string): Promise<string> {
const contentType = response.headers.get("content-type") || "";
if (contentType.includes("application/json")) {
@@ -602,7 +647,7 @@ async function publishProjectArchiveDirect(
const payload = await readJson(response);
const publishedProject = parsePublishedProjectResponse(payload);
if (!response.ok || !publishedProject) {
- throw new Error(await readErrorMessage(response, "Failed to publish project"));
+ throw await metadataRequestError(response, "Failed to publish project");
}
return publishedProject;
@@ -666,7 +711,7 @@ async function publishProjectArchiveStaged(
const uploadPayload = await readJson(uploadResponse);
const stagedUpload = parseStagedUploadResponse(uploadPayload, archive.buffer.byteLength);
if (!uploadResponse.ok || !stagedUpload) {
- throw new Error(await readErrorMessage(uploadResponse, "Failed to prepare project upload"));
+ throw await metadataRequestError(uploadResponse, "Failed to prepare project upload");
}
await uploadArchiveToPresignedUrl(stagedUpload, archive);
@@ -694,7 +739,7 @@ async function publishProjectArchiveStaged(
const completePayload = await readJson(completeResponse);
const publishedProject = parsePublishedProjectResponse(completePayload);
if (!completeResponse.ok || !publishedProject) {
- throw new Error(await readErrorMessage(completeResponse, "Failed to publish project"));
+ throw await metadataRequestError(completeResponse, "Failed to publish project");
}
return publishedProject;
@@ -714,6 +759,8 @@ export interface PublishOptions {
* minimal-repro publish) keep today's behavior unchanged.
*/
archive?: PublishArchiveResult;
+ /** The credential the caller already checked; `null` publishes anonymously. Resolved here when omitted. */
+ credential?: ResolvedCredential | null;
}
export async function publishProjectArchive(
@@ -724,7 +771,7 @@ export async function publishProjectArchive(
const title = basename(projectDir);
const archive = opts.archive ?? createPublishArchive(projectDir);
const apiBaseUrl = getPublishApiBaseUrl();
- const credential = await tryResolveCredential();
+ const credential = await resolvePublishCredential(opts.credential);
const authHeaders = credential ? buildAuthHeaders(credential) : {};
// A stable id / team space only mean something to an authenticated owner — the server
// ignores them otherwise, and anonymous publishes always mint a fresh project.
@@ -733,25 +780,37 @@ export async function publishProjectArchive(
// X-Space-Id rides with the auth headers on the metadata requests only (never the
// presigned S3 PUT), so the server resolves the shared team space instead of the personal one.
const metadataHeaders = spaceId ? { ...authHeaders, "x-space-id": spaceId } : authHeaders;
- const result =
- (await publishProjectArchiveStaged(
- apiBaseUrl,
- title,
- archive,
- isPublic,
- metadataHeaders,
- projectId,
- )) ??
- (await publishProjectArchiveDirect(
- apiBaseUrl,
- title,
- archive,
- isPublic,
- metadataHeaders,
- projectId,
- ));
+ let result: PublishedProjectResponse;
+ try {
+ result =
+ (await publishProjectArchiveStaged(
+ apiBaseUrl,
+ title,
+ archive,
+ isPublic,
+ metadataHeaders,
+ projectId,
+ )) ??
+ (await publishProjectArchiveDirect(
+ apiBaseUrl,
+ title,
+ archive,
+ isPublic,
+ metadataHeaders,
+ projectId,
+ ));
+ // Only a bearer login owns a publish; the server drops one it cannot verify.
+ if (credential?.type === "oauth" && !result.claimed) {
+ throw new CredentialRejectedError("unclaimed publish");
+ }
+ } catch (error) {
+ if (error instanceof CredentialRejectedError && credential) {
+ throw new Error(rejectedCredentialMessage(credential));
+ }
+ throw error;
+ }
// Remember the server's id + url so the next publish of this directory updates in place.
- if (credential) {
+ if (result.claimed) {
writeProjectLink(projectDir, { projectId: result.projectId, url: result.url });
}
return result;