Skip to content

Commit e0bc7cd

Browse files
committed
fix(cli): address code-review findings on OAuth PR
1 parent bb59411 commit e0bc7cd

20 files changed

Lines changed: 1606 additions & 118 deletions
Lines changed: 54 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,54 @@
1+
/**
2+
* Shared fixtures for auth-module tests. Centralises the env-snapshot
3+
* + tmp-config-dir pattern so resolver.test.ts and oauth.test.ts don't
4+
* each maintain a copy of the same beforeEach/afterEach plumbing.
5+
*
6+
* Only loaded by `*.test.ts` — runtime code doesn't depend on it.
7+
*/
8+
9+
import { promises as fs } from "node:fs";
10+
import { tmpdir } from "node:os";
11+
import { join } from "node:path";
12+
13+
const ENV_KEYS = [
14+
"HEYGEN_API_KEY",
15+
"HYPERFRAMES_API_KEY",
16+
"HEYGEN_CONFIG_DIR",
17+
"HEYGEN_API_URL",
18+
"HYPERFRAMES_OAUTH_CLIENT_ID",
19+
] as const;
20+
21+
type EnvKey = (typeof ENV_KEYS)[number];
22+
23+
export interface EnvFixture {
24+
/** Tmp config dir; deleted on `restore()`. */
25+
dir: string;
26+
/** Restore env + delete tmp dir. Idempotent. */
27+
restore: () => Promise<void>;
28+
}
29+
30+
/**
31+
* Take a snapshot of the auth-related env, clear them, make a tmp
32+
* `HEYGEN_CONFIG_DIR`, and return a `restore()` that undoes all of
33+
* the above.
34+
*/
35+
export async function setupTempAuthEnv(prefix = "hf-auth-test-"): Promise<EnvFixture> {
36+
const dir = await fs.mkdtemp(join(tmpdir(), prefix));
37+
const saved: Partial<Record<EnvKey, string | undefined>> = {};
38+
for (const k of ENV_KEYS) {
39+
saved[k] = process.env[k];
40+
delete process.env[k];
41+
}
42+
process.env["HEYGEN_CONFIG_DIR"] = dir;
43+
44+
const restore = async (): Promise<void> => {
45+
for (const k of ENV_KEYS) {
46+
const v = saved[k];
47+
if (v === undefined) delete process.env[k];
48+
else process.env[k] = v;
49+
}
50+
await fs.rm(dir, { recursive: true, force: true });
51+
};
52+
53+
return { dir, restore };
54+
}

‎packages/cli/src/auth/browser.ts‎

Lines changed: 36 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,36 @@
1+
/**
2+
* Open a URL in the user's default browser. Falls back to printing the
3+
* URL when no browser is openable (SSH session, CI, `BROWSER=none`,
4+
* or `open` rejects).
5+
*/
6+
7+
import { c } from "../ui/colors.js";
8+
9+
export interface OpenBrowserResult {
10+
/** True when we successfully invoked the platform "open" command. */
11+
opened: boolean;
12+
}
13+
14+
export async function openBrowser(url: string): Promise<OpenBrowserResult> {
15+
if (process.env["BROWSER"] === "none" || process.env["HF_NO_BROWSER"] === "1") {
16+
printManualInstructions(url);
17+
return { opened: false };
18+
}
19+
try {
20+
const open = (await import("open")).default;
21+
await open(url);
22+
return { opened: true };
23+
} catch (err) {
24+
printManualInstructions(url, err instanceof Error ? err.message : String(err));
25+
return { opened: false };
26+
}
27+
}
28+
29+
function printManualInstructions(url: string, detail?: string): void {
30+
if (detail) {
31+
console.error(c.warn(`Could not open browser automatically (${detail}).`));
32+
} else {
33+
console.error(c.warn("Browser auto-open is disabled."));
34+
}
35+
console.error(`Open this URL manually to continue:\n ${c.accent(url)}`);
36+
}

‎packages/cli/src/auth/client.test.ts‎

Lines changed: 73 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -151,6 +151,79 @@ describe("auth/client", () => {
151151
throw new Error("expected rejection");
152152
});
153153

154+
it("getCurrentUser retries once on 401 when refresh hook is configured for OAuth", async () => {
155+
let callCount = 0;
156+
const observed: string[] = [];
157+
const fetchImpl = (async (_url: string, init?: RequestInit) => {
158+
callCount++;
159+
const headers = (init?.headers as Record<string, string>) ?? {};
160+
observed.push(headers["authorization"] ?? "");
161+
if (callCount === 1) return new Response("expired", { status: 401 });
162+
return new Response(JSON.stringify({ email: "a@b" }), {
163+
status: 200,
164+
headers: { "content-type": "application/json" },
165+
});
166+
}) as unknown as typeof fetch;
167+
168+
const client = new AuthClient({
169+
baseUrl: "https://api.test.example",
170+
fetchImpl,
171+
onUnauthenticatedRefresh: async () => "fresh_at",
172+
});
173+
const user = await client.getCurrentUser({
174+
type: "oauth",
175+
access_token: "stale_at",
176+
refresh_token: "rt",
177+
source: "file_json",
178+
refreshable: true,
179+
});
180+
expect(user.email).toBe("a@b");
181+
expect(observed[0]).toBe("Bearer stale_at");
182+
expect(observed[1]).toBe("Bearer fresh_at");
183+
expect(callCount).toBe(2);
184+
});
185+
186+
it("getCurrentUser does NOT retry on 401 for api_key credentials", async () => {
187+
let callCount = 0;
188+
const fetchImpl = (async () => {
189+
callCount++;
190+
return new Response("invalid", { status: 401 });
191+
}) as unknown as typeof fetch;
192+
const client = new AuthClient({
193+
baseUrl: "https://api.test.example",
194+
fetchImpl,
195+
onUnauthenticatedRefresh: async () => "fresh",
196+
});
197+
await expect(client.getCurrentUser(apiKeyCred())).rejects.toSatisfy((err) => {
198+
return isAuthError(err) && (err as { code: string }).code === "UNAUTHENTICATED";
199+
});
200+
expect(callCount).toBe(1);
201+
});
202+
203+
it("getCurrentUser surfaces 401 when refresh hook returns null (refresh failed)", async () => {
204+
const fetchImpl = (async () =>
205+
new Response("nope", { status: 401 })) as unknown as typeof fetch;
206+
const { ErrRefreshFailed } = await import("./errors.js");
207+
const client = new AuthClient({
208+
baseUrl: "https://api.test.example",
209+
fetchImpl,
210+
onUnauthenticatedRefresh: async () => {
211+
throw ErrRefreshFailed("invalid_grant");
212+
},
213+
});
214+
await expect(
215+
client.getCurrentUser({
216+
type: "oauth",
217+
access_token: "stale",
218+
refresh_token: "rt",
219+
source: "file_json",
220+
refreshable: true,
221+
}),
222+
).rejects.toSatisfy((err) => {
223+
return isAuthError(err) && (err as { code: string }).code === "UNAUTHENTICATED";
224+
});
225+
});
226+
154227
it("getCurrentUser sends the right header for oauth credentials", async () => {
155228
let captured: Record<string, string> = {};
156229
const fetchImpl = (async (_url: string, init?: RequestInit) => {

‎packages/cli/src/auth/client.ts‎

Lines changed: 51 additions & 20 deletions
Original file line numberDiff line numberDiff line change
@@ -15,8 +15,9 @@
1515
* `movio/api_service/app/controller/user_v3.py`.
1616
*/
1717

18-
import { ErrApi, ErrUnauthenticated } from "./errors.js";
18+
import { ErrApi, ErrUnauthenticated, isAuthError } from "./errors.js";
1919
import type { ResolvedCredential } from "./resolver.js";
20+
import { scrubCredentials } from "./scrub.js";
2021

2122
const DEFAULT_BASE_URL = "https://api.heygen.com";
2223

@@ -63,27 +64,63 @@ export interface AuthClientOptions {
6364
baseUrl?: string;
6465
/** Inject a custom fetch (used by tests). */
6566
fetchImpl?: typeof fetch;
67+
/**
68+
* Hook for refreshing an OAuth credential on 401. The hook should
69+
* exchange the supplied refresh_token for new tokens, persist them,
70+
* and return the new bearer to retry with. Wired in by the auth
71+
* commands; injectable for tests.
72+
*/
73+
onUnauthenticatedRefresh?: (refresh_token: string) => Promise<string>;
6674
}
6775

6876
export class AuthClient {
6977
private readonly base: string;
7078
private readonly fetchImpl: typeof fetch;
79+
private readonly onRefresh?: (refresh_token: string) => Promise<string>;
7180

7281
constructor(opts: AuthClientOptions = {}) {
7382
this.base = (opts.baseUrl ?? apiBaseUrl()).replace(/\/+$/, "");
7483
this.fetchImpl = opts.fetchImpl ?? fetch;
84+
this.onRefresh = opts.onUnauthenticatedRefresh;
7585
}
7686

7787
/**
7888
* `GET /v3/users/me`. Throws `ErrUnauthenticated` on 401, `ErrApi`
7989
* on any other non-2xx or non-JSON body.
90+
*
91+
* On OAuth 401 with a refresh hook configured, the request is
92+
* retried once after refreshing the access token. The retry's
93+
* outcome is what the caller sees — if the refresh itself fails
94+
* (REFRESH_FAILED) or the retry still 401s, the user lands on a
95+
* "please log in again" path upstream.
8096
*/
8197
async getCurrentUser(credential: ResolvedCredential): Promise<UserInfo> {
8298
const url = `${this.base}/v3/users/me`;
99+
return await this.fetchUser(url, credential, true);
100+
}
101+
102+
// fallow-ignore-next-line complexity
103+
private async fetchUser(
104+
url: string,
105+
credential: ResolvedCredential,
106+
allowRefresh: boolean,
107+
): Promise<UserInfo> {
83108
const headers = buildAuthHeaders(credential);
84109
const res = await this.fetchImpl(url, { method: "GET", headers });
85110

86111
if (res.status === 401) {
112+
if (
113+
allowRefresh &&
114+
credential.type === "oauth" &&
115+
credential.refresh_token &&
116+
this.onRefresh
117+
) {
118+
const refreshed = await this.tryRefresh(credential.refresh_token);
119+
if (refreshed) {
120+
const next: ResolvedCredential = { ...credential, access_token: refreshed };
121+
return await this.fetchUser(url, next, false);
122+
}
123+
}
87124
const detail = await safeText(res);
88125
throw ErrUnauthenticated(detail || `${res.status} ${res.statusText}`);
89126
}
@@ -99,6 +136,19 @@ export class AuthClient {
99136
}
100137
return extractUserInfo(payload);
101138
}
139+
140+
private async tryRefresh(refresh_token: string): Promise<string | null> {
141+
if (!this.onRefresh) return null;
142+
try {
143+
return await this.onRefresh(refresh_token);
144+
} catch (err) {
145+
// Refresh failure should be surfaced upstream by the caller via
146+
// the retry's 401, not by throwing here — so callers consistently
147+
// see "please log in again" rather than mixed error types.
148+
if (isAuthError(err) && err.code === "REFRESH_FAILED") return null;
149+
throw err;
150+
}
151+
}
102152
}
103153

104154
export function buildAuthHeaders(credential: ResolvedCredential): Record<string, string> {
@@ -117,25 +167,6 @@ async function safeText(res: Response): Promise<string> {
117167
}
118168
}
119169

120-
/**
121-
* Strip credential-shaped substrings from error bodies before they
122-
* surface in user-facing messages or `--json` output. Some proxies
123-
* echo request headers in their error pages and we never want a
124-
* HeyGen API key, OAuth bearer, or JWT to land in scrollback / CI
125-
* logs because of one of those echoes.
126-
*/
127-
function scrubCredentials(s: string): string {
128-
return (
129-
s
130-
.replace(/hg_[A-Za-z0-9_-]{4,}/g, "hg_<redacted>")
131-
// Redact the ENTIRE header value to end-of-line — `Bearer <token>`
132-
// is two whitespace-separated words, so a `\S+` would leave the
133-
// opaque token exposed after the scheme.
134-
.replace(/(authorization|x-api-key)[ \t]*[:=][ \t]*[^\r\n]+/gi, "$1: <redacted>")
135-
.replace(/\beyJ[A-Za-z0-9_-]{8,}\.[A-Za-z0-9_-]+\.[A-Za-z0-9_-]+/g, "<jwt-redacted>")
136-
);
137-
}
138-
139170
/**
140171
* The backend wraps responses in `{code, message, data: {...}}` for some
141172
* endpoints and returns raw fields directly for others. Handle both.

‎packages/cli/src/auth/errors.ts‎

Lines changed: 21 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -3,7 +3,13 @@
33
* can map specific failures to friendly UX without parsing messages.
44
*/
55

6-
export type AuthErrorCode = "NOT_CONFIGURED" | "INVALID_STORE" | "API_ERROR" | "UNAUTHENTICATED";
6+
export type AuthErrorCode =
7+
| "NOT_CONFIGURED"
8+
| "INVALID_STORE"
9+
| "API_ERROR"
10+
| "UNAUTHENTICATED"
11+
| "OAUTH_NOT_CONFIGURED"
12+
| "REFRESH_FAILED";
713

814
export class AuthError extends Error {
915
readonly code: AuthErrorCode;
@@ -41,6 +47,20 @@ export const ErrUnauthenticated = (detail?: string) =>
4147
export const ErrApi = (status: number, detail: string) =>
4248
new AuthError("API_ERROR", `HeyGen API error (${status}): ${detail}`);
4349

50+
export const ErrOAuthNotConfigured = () =>
51+
new AuthError(
52+
"OAUTH_NOT_CONFIGURED",
53+
"OAuth client is not configured",
54+
"Set HYPERFRAMES_OAUTH_CLIENT_ID, or run `hyperframes auth login --api-key`.",
55+
);
56+
57+
export const ErrRefreshFailed = (detail?: string) =>
58+
new AuthError(
59+
"REFRESH_FAILED",
60+
detail ? `Failed to refresh OAuth tokens: ${detail}` : "Failed to refresh OAuth tokens",
61+
"Run `hyperframes auth login` to re-authenticate.",
62+
);
63+
4464
export function isAuthError(err: unknown): err is AuthError {
4565
return err instanceof AuthError;
4666
}

‎packages/cli/src/auth/index.ts‎

Lines changed: 7 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -15,3 +15,10 @@ export type { ResolvedCredential } from "./resolver.js";
1515

1616
export { AuthClient } from "./client.js";
1717
export type { UserInfo } from "./client.js";
18+
19+
export {
20+
assertOAuthConfiguredOrExit,
21+
refreshTokens,
22+
revokeTokens,
23+
startAuthorizationCodeFlow,
24+
} from "./oauth.js";

0 commit comments

Comments
 (0)