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" ;
1919import type { ResolvedCredential } from "./resolver.js" ;
20+ import { scrubCredentials } from "./scrub.js" ;
2021
2122const 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
6876export 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
104154export 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 ( / h g _ [ A - Z a - z 0 - 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 ( / ( a u t h o r i z a t i o n | x - a p i - k e y ) [ \t ] * [: = ] [ \t ] * [ ^ \r \n ] + / gi, "$1: <redacted>" )
135- . replace ( / \b e y J [ A - Z a - z 0 - 9 _ - ] { 8 , } \. [ A - Z a - z 0 - 9 _ - ] + \. [ A - Z a - z 0 - 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.
0 commit comments