mirror of
https://github.com/heygen-com/hyperframes.git
synced 2026-11-18 16:08:56 +00:00
* fix(cli): an interrupted templates pull leaves no partial folder Unpacking now runs tar asynchronously and removes its .part folder on SIGINT/SIGTERM/SIGHUP before re-raising the signal. Part folders carry the owning pid, and the next pull clears any whose process is gone. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> * fix(cli): auth status and templates pull say when HeyGen cannot be reached Offline, both commands waited on unbounded requests and then printed only undici's 'fetch failed'. A new networkFailure helper names the host, the reason (DNS lookup, no route, refused, no answer in time, dropped) and the next step. The account and token-refresh requests now time out after 15 s, the template link after 15 s, and auth status reports an offline refresh at once instead of retrying with the stale token. describeCauseChain moves into the helper so the registry and auth share it. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> * fix(cli): preview leaves the project's HTML files as they are Opening a project in preview stamped data-hf-id into every composition on disk. The preview route and every source mutation already mint the same content-keyed ids in memory, so the startup pass is dropped: files gain ids only when an edit to them is saved. The .hyperframes folder is still made before the watcher starts, so the preview cache creating it is not reported to Studio as a manifest change. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> * fix(cli): check runs the browser audits past a lint error A lint error made check skip runtime, layout, motion and contrast, so one known lint error hid every browser finding. The browser pass now runs whenever there is a composition to load, and the lint error still fails the check. Only a root with no data-composition-id skips it. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> * fix(cli): no desktop-app line for CI or a script reading render output The 'Keep editing by chatting with Framey' line printed on every render and preview, including CI and piped runs where nobody can open the app. It now prints for a person at a terminal, and for a coding agent, which the hyperframes skill tells to pass the line on; CI and other non-TTY runs get nothing. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> * fix(cli): cloud render takes a composition at any aspect ratio A 1920x960 composition got 'server will default aspect_ratio to 16:9' although the render kept 1920x960: at 1080p the cloud renders at the composition's own size and aspect_ratio only picks a 4K preset. The CLI now names the detected ratio (2:1) and says the size is kept, takes --aspect-ratio as any W:H checked against the composition, sends only the 16:9, 9:16 and 1:1 the API accepts, and refuses a 4K render of any other ratio before upload, where no preset fits. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> * fix(media-use): a weak sound-effect match says so instead of passing silently resolve --type sfx returned a HeyGen sound at any score down to 0.4, and a project file that shared one word of its name with the intent, with nothing to tell them from a real match. Such a result now carries a match object in the JSON ({score, min_score, low_confidence} or the matched words and the intent the file was resolved for) and a low-confidence line on stderr. A HeyGen search with no hit says so with the min score it used, and a sound effect nothing matches fails with 'no sound effect matched'. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> * feat(cli): media-use avatars lists the film account's avatar looks Templates had to reach for 'heygen avatar list', a separate sign-in that can be another account. 'media-use avatars' lists the private looks on the HyperFrames account making the film (GET /v3/avatars/looks?ownership=private, following next_token up to --limit) as {avatars: [{avatar_id, name, ...}]}, the id that 'generate --type avatar --avatar' takes. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> * chore(skills): leave style-sampling's avatar line to #7164, which owns that skill Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> * fix(cli): templates pull removes only the part folders it marked as its own The abandoned-part cleanup deleted any sibling named '<slug>.part-*' whose next token was not a live pid, so a person's own 'sample.part-notes/', 'sample.part-reference.txt' or a symlink went with it. A pull now writes an ownership marker (owner tag + pid) into its part folder, and the cleanup removes only a real directory with the generated '<slug>.part-<pid>-XXXXXX' name whose marker names a dead pid. Files, symlinks, unmarked folders and older unmarked parts are left alone. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> * fix(cli): media-use avatars says it is offline when the login refresh cannot reach HeyGen A network failure while refreshing the stored login was reported as 'no HeyGen sign-in' with 'auth login' as the fix, though the login was still there. It now keeps the network failure's message and next step. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> * fix(media-use): a reused weak sound keeps its low-confidence advisory The first resolve of a weak HeyGen sound or a name-matched project file flagged it, but an identical second resolve hit the project manifest and returned it with no match object. The advisory is now rebuilt from the record's provenance (the stored score, or the adopted file's name) on reuse. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> * refactor(cli): keep the comment share of files this branch touched from rising Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> * fix(cli): no check-then-use on pull markers, and the download is never written to disk CodeQL flagged the downloaded bundle written to a file before tar read it, and a stat-then-read in the preview test. The verified archive now streams into tar's stdin, so no network bytes reach a file the CLI writes. The abandoned-part scan takes the entry type from readdir instead of an lstat, reads the ownership marker through one O_NOFOLLOW descriptor it fstats, and the preview test reads each file once instead of stat-checking it first. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> * chore(ci): raise the CLI's unpacked size budget to 5% over its measured size main's @hyperframes/cli was already about 0.99% over its 23722874-byte unpacked budget, so this branch's additions (networkFailure, the avatars command, the larger skill references) tip it past the 1% tolerance. This is the same value #7169 sets, 25159107 bytes (5% headroom over the measured size), so the two PRs merge cleanly. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> * refactor(cli): split the pull-marker check and share the token-endpoint POST Fallow flagged pullOwner (CRAP 49.5, cyclomatic 13) and a 28-line clone between refreshOnce and exchangeCodeForTokens. pullOwner is now the name match, the O_NOFOLLOW marker read and the marker check as three small functions, with the same behaviour. Both token requests go through one postToTokenEndpoint, which keeps the 15 s timeout and the named network failure. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> * fix(cli): a 4k cloud render checks the exact size against its preset before upload The aspect detector matches a ratio within ±0.05, so at 4k a 1920x1055 composition was sent as 16:9 and 1000x980 as 1:1, and the producer then refused both as an aspect mismatch. At 4k the matched ratio's preset (landscape-4k, portrait-4k, square-4k, the ones the API maps it to) now goes through the producer's own checkOutputResolutionCompatibility, and a composition it does not fit is refused locally with the producer's reason and the 1080p alternative. 1080p, where the render keeps the composition's own size, is unchanged. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> --------- Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com>
847 lines
28 KiB
TypeScript
847 lines
28 KiB
TypeScript
import { failCommand } from "../utils/commandResult.js";
|
|
/**
|
|
* OAuth 2.0 + PKCE driver for the HeyGen public OAuth flow.
|
|
*
|
|
* Entry points:
|
|
* - `startAuthorizationCodeFlow()` — full interactive login (browser
|
|
* opens, loopback waits, code → tokens, persist).
|
|
* - `refreshTokens()` — POST <token-endpoint> with grant_type=refresh_token.
|
|
* - `revokeTokens()` — best-effort POST <revoke-endpoint>.
|
|
*
|
|
* Endpoints split across two hosts (verified live):
|
|
* - **Authorize** — GET https://app.heygen.com/oauth/authorize
|
|
* Renders the consent screen, has to live on the same origin as the
|
|
* user's web session (cookies). The Next.js SPA shell serves this.
|
|
* - **Token** — POST https://api2.heygen.com/v1/oauth/token
|
|
* Server-to-server JSON API. `app.heygen.com/oauth/token` returns
|
|
* the SPA HTML for direct POSTs — confirmed by curl; only the api2
|
|
* route returns JSON OAuth responses.
|
|
* - **Revoke** — POST https://api2.heygen.com/v1/oauth/revoke
|
|
* Same host/prefix as token.
|
|
*
|
|
* `app.heygen.com/oauth/token` returns the SPA shell on a direct fetch, so we
|
|
* use the api2 endpoint here.
|
|
*
|
|
* Overrides:
|
|
* - `HYPERFRAMES_OAUTH_AUTHORIZE_URL`
|
|
* - `HYPERFRAMES_OAUTH_TOKEN_URL`
|
|
* - `HYPERFRAMES_OAUTH_REVOKE_URL`
|
|
* - `HYPERFRAMES_OAUTH_CLIENT_ID`
|
|
*
|
|
* Public client — no `client_secret`.
|
|
*/
|
|
|
|
import {
|
|
ErrApi,
|
|
ErrDeviceAuthFailed,
|
|
ErrLoginChanged,
|
|
ErrRefreshFailed,
|
|
isAuthError,
|
|
} from "./errors.js";
|
|
import { generatePkcePair, generateState } from "./pkce.js";
|
|
import { startLoopback } from "./loopback.js";
|
|
import { openBrowser } from "./browser.js";
|
|
import { scrubCredentials } from "./scrub.js";
|
|
import { ACCOUNT_REQUEST_TIMEOUT_MS } from "./client.js";
|
|
import { explainNetworkFailure } from "../utils/networkFailure.js";
|
|
import {
|
|
isHeaderSafe,
|
|
readStore,
|
|
writeStore,
|
|
type Credentials,
|
|
type OAuthTokens,
|
|
type StoredUserInfo,
|
|
} from "./store.js";
|
|
import { c } from "../ui/colors.js";
|
|
import {
|
|
assertOAuthIdentity,
|
|
authorizeEndpoint,
|
|
deviceAuthorizationEndpoint,
|
|
oauthIdentity,
|
|
resolveClientId,
|
|
revokeEndpoint,
|
|
tokenEndpoint,
|
|
} from "./config.js";
|
|
|
|
export { resolveClientId } from "./config.js";
|
|
|
|
const REVOKE_TIMEOUT_MS = 5_000;
|
|
const MIN_EXPIRES_IN_SECONDS = 30;
|
|
|
|
const DEFAULT_SCOPES = "openid profile email";
|
|
|
|
const DEVICE_CODE_GRANT_TYPE = "urn:ietf:params:oauth:grant-type:device_code";
|
|
const MAX_DEVICE_FLOW_SECONDS = 30 * 60;
|
|
const MIN_DEVICE_POLL_SECONDS = 5;
|
|
const MAX_DEVICE_POLL_SECONDS = 60;
|
|
const MAX_DEVICE_RESPONSE_BYTES = 64 * 1024;
|
|
const DEVICE_REQUEST_TIMEOUT_MS = 15_000;
|
|
|
|
export interface AuthorizeFlowOptions {
|
|
/** Override scopes (default `openid profile email`). */
|
|
scope?: string;
|
|
/** Inject a custom fetch (used by tests). */
|
|
fetchImpl?: typeof fetch;
|
|
/** Override timeout in ms (default 60 minutes). */
|
|
timeoutMs?: number;
|
|
}
|
|
|
|
export interface AuthorizeFlowResult {
|
|
tokens: OAuthTokens;
|
|
/** Returned identity info for friendly post-login UX. */
|
|
userInfo?: Record<string, unknown>;
|
|
}
|
|
|
|
export interface RefreshOptions {
|
|
fetchImpl?: typeof fetch;
|
|
}
|
|
|
|
export interface DeviceAuthorizationChallenge {
|
|
userCode: string;
|
|
verificationUri: string;
|
|
verificationUriComplete?: string;
|
|
}
|
|
|
|
export interface DeviceAuthorizationFlowOptions {
|
|
/** Override scopes (default `openid profile email`). */
|
|
scope?: string;
|
|
/** Inject a custom fetch (used by tests). */
|
|
fetchImpl?: typeof fetch;
|
|
/** Inject polling sleep (used by tests). */
|
|
sleepImpl?: (ms: number) => Promise<void>;
|
|
/** Inject a monotonic-enough clock in epoch milliseconds (used by tests). */
|
|
now?: () => number;
|
|
/** Bound each authorization-server request, including its response body (default 15s). */
|
|
requestTimeoutMs?: number;
|
|
/** Present the user code and verification URI without exposing device_code. */
|
|
onChallenge?: (challenge: DeviceAuthorizationChallenge) => void | Promise<void>;
|
|
}
|
|
|
|
/**
|
|
* For command-entry points: throw the standard `ErrOAuthNotConfigured`
|
|
* via `resolveClientId()`; on a real misconfig, print a friendly hint
|
|
* and exit with status 1 rather than dumping a stack. Throws non-auth
|
|
* errors so callers can surface programmer bugs.
|
|
*/
|
|
export function assertOAuthConfiguredOrExit(): void {
|
|
try {
|
|
resolveClientId();
|
|
} catch (err) {
|
|
if (isAuthError(err) && err.code === "OAUTH_NOT_CONFIGURED") {
|
|
console.error(`Error: ${err.message}`);
|
|
if (err.hint) console.error(err.hint);
|
|
failCommand();
|
|
}
|
|
throw err;
|
|
}
|
|
}
|
|
|
|
export async function startAuthorizationCodeFlow(
|
|
opts: AuthorizeFlowOptions = {},
|
|
): Promise<AuthorizeFlowResult> {
|
|
const clientId = resolveClientId();
|
|
const scope = opts.scope ?? DEFAULT_SCOPES;
|
|
const pkce = generatePkcePair();
|
|
const state = generateState();
|
|
|
|
const loopback = await startLoopback({ state, timeoutMs: opts.timeoutMs });
|
|
let codeResult;
|
|
try {
|
|
const authorizeUrl = buildAuthorizeUrl({
|
|
clientId,
|
|
redirectUri: loopback.redirectUri,
|
|
scope,
|
|
state,
|
|
challenge: pkce.challenge,
|
|
});
|
|
|
|
// Print the host+path only (no state / code_challenge) so live
|
|
// values can't leak into scrollback / CI logs during the wait.
|
|
console.log(`Opening browser to ${c.dim(authorizeHost(authorizeUrl))} ...`);
|
|
const { opened } = await openBrowser(authorizeUrl);
|
|
if (!opened) {
|
|
// openBrowser already printed the manual URL; surface it as the
|
|
// last on-screen instruction so it isn't buried above "Waiting…".
|
|
console.log(c.dim("(open the URL above to continue)"));
|
|
}
|
|
console.log(
|
|
`Waiting for callback on ${c.accent(loopback.redirectUri)} (up to ${loopback.timeoutLabel}, Ctrl+C to cancel) ...`,
|
|
);
|
|
|
|
codeResult = await loopback.result;
|
|
} finally {
|
|
await loopback.close().catch(() => {});
|
|
}
|
|
|
|
const tokens = await exchangeCodeForTokens({
|
|
clientId,
|
|
code: codeResult.code,
|
|
redirectUri: codeResult.redirectUri,
|
|
verifier: pkce.verifier,
|
|
fetchImpl: opts.fetchImpl,
|
|
});
|
|
|
|
// Fresh login → clean OAuth block (no inherited refresh_token).
|
|
await persistOAuth(tokens);
|
|
return { tokens };
|
|
}
|
|
|
|
/**
|
|
* RFC 8628 attended device flow. This function deliberately returns an
|
|
* unpersisted token set: the command must verify `/v3/users/me` first and only
|
|
* then call `persistFreshOAuth`. That ordering prevents a token for the wrong
|
|
* account/resource from ever becoming the active HyperFrames credential.
|
|
*/
|
|
export async function startDeviceAuthorizationFlow(
|
|
opts: DeviceAuthorizationFlowOptions = {},
|
|
): Promise<OAuthTokens> {
|
|
const runtime: DeviceFlowRuntime = {
|
|
clientId: resolveClientId(),
|
|
fetchImpl: opts.fetchImpl ?? fetch,
|
|
sleepImpl:
|
|
opts.sleepImpl ?? ((ms: number) => new Promise((resolve) => setTimeout(resolve, ms))),
|
|
now: opts.now ?? Date.now,
|
|
requestTimeoutMs: opts.requestTimeoutMs ?? DEVICE_REQUEST_TIMEOUT_MS,
|
|
};
|
|
const issuance = await requestDeviceAuthorization(runtime, opts.scope ?? DEFAULT_SCOPES);
|
|
await opts.onChallenge?.({
|
|
userCode: issuance.userCode,
|
|
verificationUri: issuance.verificationUri,
|
|
...(issuance.verificationUriComplete
|
|
? { verificationUriComplete: issuance.verificationUriComplete }
|
|
: {}),
|
|
});
|
|
return await pollDeviceToken(runtime, issuance);
|
|
}
|
|
|
|
interface DeviceFlowRuntime {
|
|
clientId: string;
|
|
fetchImpl: typeof fetch;
|
|
sleepImpl: (ms: number) => Promise<void>;
|
|
now: () => number;
|
|
requestTimeoutMs: number;
|
|
}
|
|
|
|
async function requestDeviceAuthorization(
|
|
runtime: DeviceFlowRuntime,
|
|
scope: string,
|
|
): Promise<ParsedDeviceAuthorization> {
|
|
return await withDeviceRequestTimeout(
|
|
runtime,
|
|
"could not reach the authorization server",
|
|
async (signal) => {
|
|
const response = await runtime.fetchImpl(deviceAuthorizationEndpoint(), {
|
|
method: "POST",
|
|
headers: {
|
|
"content-type": "application/x-www-form-urlencoded",
|
|
accept: "application/json",
|
|
},
|
|
body: new URLSearchParams({ client_id: runtime.clientId, scope }).toString(),
|
|
signal,
|
|
});
|
|
if (!response.ok) {
|
|
throw ErrDeviceAuthFailed(`authorization server returned HTTP ${response.status}`);
|
|
}
|
|
return parseDeviceAuthorizationResponse(await readJsonOrDeviceError(response));
|
|
},
|
|
);
|
|
}
|
|
|
|
async function pollDeviceToken(
|
|
runtime: DeviceFlowRuntime,
|
|
issuance: ParsedDeviceAuthorization,
|
|
): Promise<OAuthTokens> {
|
|
const deadline = runtime.now() + Math.min(issuance.expiresIn, MAX_DEVICE_FLOW_SECONDS) * 1000;
|
|
let intervalSeconds = issuance.interval;
|
|
while (runtime.now() < deadline) {
|
|
const remainingMs = deadline - runtime.now();
|
|
if (remainingMs <= 0) break;
|
|
await runtime.sleepImpl(Math.min(intervalSeconds * 1000, remainingMs));
|
|
|
|
const result = await requestDeviceToken(runtime, issuance.deviceCode);
|
|
if (result.tokens) return result.tokens;
|
|
if (result.slowDown) {
|
|
intervalSeconds = Math.min(
|
|
Math.max(intervalSeconds + 5, result.retryAfterSeconds ?? 0),
|
|
MAX_DEVICE_POLL_SECONDS,
|
|
);
|
|
}
|
|
}
|
|
throw ErrDeviceAuthFailed("the code expired");
|
|
}
|
|
|
|
async function requestDeviceToken(
|
|
runtime: DeviceFlowRuntime,
|
|
deviceCode: string,
|
|
): Promise<DevicePollResult> {
|
|
return await withDeviceRequestTimeout(
|
|
runtime,
|
|
"lost contact with the authorization server",
|
|
async (signal) => {
|
|
const response = await runtime.fetchImpl(tokenEndpoint(), {
|
|
method: "POST",
|
|
headers: {
|
|
"content-type": "application/x-www-form-urlencoded",
|
|
accept: "application/json",
|
|
},
|
|
body: new URLSearchParams({
|
|
grant_type: DEVICE_CODE_GRANT_TYPE,
|
|
device_code: deviceCode,
|
|
client_id: runtime.clientId,
|
|
}).toString(),
|
|
signal,
|
|
});
|
|
return await evaluateDevicePollResponse(response, runtime.now());
|
|
},
|
|
);
|
|
}
|
|
|
|
interface DevicePollResult {
|
|
tokens?: OAuthTokens;
|
|
slowDown?: boolean;
|
|
retryAfterSeconds?: number;
|
|
}
|
|
|
|
async function evaluateDevicePollResponse(
|
|
response: Response,
|
|
nowMs: number,
|
|
): Promise<DevicePollResult> {
|
|
if (response.ok) {
|
|
return { tokens: parseTokenResponse(await readJsonOrDeviceError(response)) };
|
|
}
|
|
|
|
const error = await readDeviceOAuthError(response);
|
|
switch (error) {
|
|
case "authorization_pending":
|
|
return {};
|
|
case "slow_down":
|
|
return { slowDown: true, retryAfterSeconds: retryAfterSeconds(response, nowMs) };
|
|
case "access_denied":
|
|
throw ErrDeviceAuthFailed("access was denied");
|
|
case "expired_token":
|
|
throw ErrDeviceAuthFailed("the code expired");
|
|
default:
|
|
if (response.status === 429) {
|
|
return { slowDown: true, retryAfterSeconds: retryAfterSeconds(response, nowMs) };
|
|
}
|
|
throw ErrDeviceAuthFailed(`authorization server returned HTTP ${response.status}`);
|
|
}
|
|
}
|
|
|
|
async function withDeviceRequestTimeout<T>(
|
|
runtime: DeviceFlowRuntime,
|
|
networkError: string,
|
|
operation: (signal: AbortSignal) => Promise<T>,
|
|
): Promise<T> {
|
|
const controller = new AbortController();
|
|
const timer = setTimeout(() => controller.abort(), runtime.requestTimeoutMs);
|
|
try {
|
|
return await operation(controller.signal);
|
|
} catch (err) {
|
|
if (controller.signal.aborted) {
|
|
throw ErrDeviceAuthFailed("authorization server request timed out");
|
|
}
|
|
if (isAuthError(err)) throw err;
|
|
throw ErrDeviceAuthFailed(networkError);
|
|
} finally {
|
|
clearTimeout(timer);
|
|
}
|
|
}
|
|
|
|
function retryAfterSeconds(response: Response, nowMs: number): number | undefined {
|
|
const value = response.headers.get("retry-after")?.trim();
|
|
if (!value) return undefined;
|
|
if (/^\d+$/.test(value)) return Math.min(Number(value), MAX_DEVICE_POLL_SECONDS);
|
|
const retryAt = Date.parse(value);
|
|
if (!Number.isFinite(retryAt)) return undefined;
|
|
return Math.min(Math.max(Math.ceil((retryAt - nowMs) / 1000), 0), MAX_DEVICE_POLL_SECONDS);
|
|
}
|
|
|
|
const refreshing = new Map<string, Promise<OAuthTokens>>();
|
|
|
|
/** Refresh the stored login. Calls that overlap in this process share one request, since the server rotates the token. */
|
|
export function refreshTokens(
|
|
refresh_token: string,
|
|
opts: RefreshOptions = {},
|
|
): Promise<OAuthTokens> {
|
|
const pending = refreshing.get(refresh_token);
|
|
if (pending) return pending;
|
|
const request = refreshOnce(refresh_token, opts).finally(() => refreshing.delete(refresh_token));
|
|
refreshing.set(refresh_token, request);
|
|
return request;
|
|
}
|
|
|
|
async function postToTokenEndpoint(fetchImpl: typeof fetch, body: URLSearchParams) {
|
|
return await fetchImpl(tokenEndpoint(), {
|
|
method: "POST",
|
|
headers: {
|
|
"content-type": "application/x-www-form-urlencoded",
|
|
accept: "application/json",
|
|
},
|
|
body: body.toString(),
|
|
signal: AbortSignal.timeout(ACCOUNT_REQUEST_TIMEOUT_MS),
|
|
}).catch((error: unknown) => {
|
|
throw explainNetworkFailure(error, tokenEndpoint());
|
|
});
|
|
}
|
|
|
|
async function refreshOnce(refresh_token: string, opts: RefreshOptions): Promise<OAuthTokens> {
|
|
const { credentials } = await readStore();
|
|
if (credentials.oauth?.refresh_token !== refresh_token) throw ErrLoginChanged();
|
|
assertOAuthIdentity(credentials.oauth);
|
|
const clientId = resolveClientId();
|
|
const fetchImpl = opts.fetchImpl ?? fetch;
|
|
const body = new URLSearchParams({
|
|
grant_type: "refresh_token",
|
|
refresh_token,
|
|
client_id: clientId,
|
|
});
|
|
|
|
const res = await postToTokenEndpoint(fetchImpl, body);
|
|
|
|
if (res.status === 400 || res.status === 401) {
|
|
throw ErrRefreshFailed(await safeText(res), { refused: true });
|
|
}
|
|
if (!res.ok) {
|
|
throw ErrApi(res.status, (await safeText(res)) || res.statusText);
|
|
}
|
|
|
|
const payload = await readJsonOrThrow(res);
|
|
const tokens = parseTokenResponse(payload);
|
|
// Refresh grant → preserve a refresh_token the server didn't rotate.
|
|
await persistOAuth(tokens, { refreshed: refresh_token });
|
|
return tokens;
|
|
}
|
|
|
|
export interface RevokeOptions extends RefreshOptions {
|
|
/** Hint to the server about which token we're sending (RFC 7009). */
|
|
token_type_hint?: "access_token" | "refresh_token";
|
|
/** Abort the revoke after this many ms (default 5s). */
|
|
timeoutMs?: number;
|
|
}
|
|
|
|
/**
|
|
* RFC 7009 revoke. Best-effort: never throws. A hung IdP or unset
|
|
* client_id MUST NOT block local logout — both are caught here so the
|
|
* caller can wipe local state immediately afterward regardless.
|
|
*/
|
|
export async function revokeTokens(token: string, opts: RevokeOptions = {}): Promise<void> {
|
|
let clientId: string;
|
|
try {
|
|
clientId = resolveClientId();
|
|
const { credentials } = await readStore();
|
|
if (
|
|
credentials.oauth &&
|
|
(credentials.oauth.access_token === token || credentials.oauth.refresh_token === token)
|
|
) {
|
|
assertOAuthIdentity(credentials.oauth);
|
|
}
|
|
} catch {
|
|
// OAuth not configured — nothing to revoke server-side.
|
|
return;
|
|
}
|
|
|
|
const fetchImpl = opts.fetchImpl ?? fetch;
|
|
const params: Record<string, string> = { token, client_id: clientId };
|
|
if (opts.token_type_hint) params["token_type_hint"] = opts.token_type_hint;
|
|
const body = new URLSearchParams(params);
|
|
|
|
const controller = new AbortController();
|
|
const timer = setTimeout(() => controller.abort(), opts.timeoutMs ?? REVOKE_TIMEOUT_MS);
|
|
try {
|
|
const res = await fetchImpl(revokeEndpoint(), {
|
|
method: "POST",
|
|
headers: { "content-type": "application/x-www-form-urlencoded" },
|
|
body: body.toString(),
|
|
signal: controller.signal,
|
|
});
|
|
if (!res.ok) {
|
|
console.error(
|
|
c.dim(`Note: token revoke returned HTTP ${res.status}; local credentials cleared anyway.`),
|
|
);
|
|
}
|
|
} catch {
|
|
/* timeout or network error — silent, this is best-effort */
|
|
} finally {
|
|
clearTimeout(timer);
|
|
}
|
|
}
|
|
|
|
function authorizeHost(fullUrl: string): string {
|
|
try {
|
|
const u = new URL(fullUrl);
|
|
return `${u.origin}${u.pathname}`;
|
|
} catch {
|
|
return fullUrl.split("?")[0] ?? fullUrl;
|
|
}
|
|
}
|
|
|
|
function buildAuthorizeUrl(args: {
|
|
clientId: string;
|
|
redirectUri: string;
|
|
scope: string;
|
|
state: string;
|
|
challenge: string;
|
|
}): string {
|
|
const params = new URLSearchParams({
|
|
response_type: "code",
|
|
client_id: args.clientId,
|
|
redirect_uri: args.redirectUri,
|
|
scope: args.scope,
|
|
state: args.state,
|
|
code_challenge: args.challenge,
|
|
code_challenge_method: "S256",
|
|
});
|
|
const urlWithEndpointQuery = new URL(authorizeEndpoint());
|
|
for (const [key, value] of params) urlWithEndpointQuery.searchParams.set(key, value);
|
|
return urlWithEndpointQuery.toString();
|
|
}
|
|
|
|
async function exchangeCodeForTokens(args: {
|
|
clientId: string;
|
|
code: string;
|
|
redirectUri: string;
|
|
verifier: string;
|
|
fetchImpl?: typeof fetch;
|
|
}): Promise<OAuthTokens> {
|
|
const fetchImpl = args.fetchImpl ?? fetch;
|
|
const body = new URLSearchParams({
|
|
grant_type: "authorization_code",
|
|
code: args.code,
|
|
redirect_uri: args.redirectUri,
|
|
client_id: args.clientId,
|
|
code_verifier: args.verifier,
|
|
});
|
|
const res = await postToTokenEndpoint(fetchImpl, body);
|
|
if (res.status === 400 || res.status === 401) {
|
|
// The authorization code is single-use and short-lived. A 400/401
|
|
// here almost always means it expired during the loopback wait or
|
|
// was already redeemed — surface an actionable message instead of
|
|
// a bare "HeyGen API error (400)".
|
|
const detail = (await safeText(res)) || res.statusText;
|
|
throw ErrRefreshFailed(
|
|
`authorization code rejected (${detail}); please run \`auth login\` again`,
|
|
);
|
|
}
|
|
if (!res.ok) {
|
|
throw ErrApi(res.status, (await safeText(res)) || res.statusText);
|
|
}
|
|
return parseTokenResponse(await readJsonOrThrow(res));
|
|
}
|
|
|
|
/**
|
|
* Parse the RFC 6749 token response. Backend may also include
|
|
* `id_token` (OIDC) but we ignore that today.
|
|
*
|
|
* Throws `ErrInvalidTokenResponse` (an AuthError carrying
|
|
* REFRESH_FAILED code, so callers using `tryRefresh` consistently
|
|
* route the user to "log in again" instead of a generic API error)
|
|
* on shape failures.
|
|
*/
|
|
// fallow-ignore-next-line complexity
|
|
export function parseTokenResponse(payload: unknown): OAuthTokens {
|
|
if (!payload || typeof payload !== "object" || Array.isArray(payload)) {
|
|
throw ErrRefreshFailed("token endpoint returned a non-object payload");
|
|
}
|
|
const obj = payload as Record<string, unknown>;
|
|
const accessToken = stringField(obj, "access_token");
|
|
if (!accessToken) {
|
|
throw ErrRefreshFailed("token endpoint did not return an access_token");
|
|
}
|
|
if (!isHeaderSafe(accessToken)) {
|
|
throw ErrRefreshFailed("access_token contains control characters");
|
|
}
|
|
|
|
const out: OAuthTokens = { access_token: accessToken };
|
|
const refreshToken = stringField(obj, "refresh_token");
|
|
if (refreshToken) {
|
|
if (!isHeaderSafe(refreshToken)) {
|
|
throw ErrRefreshFailed("refresh_token contains control characters");
|
|
}
|
|
out.refresh_token = refreshToken;
|
|
}
|
|
const tokenType = stringField(obj, "token_type");
|
|
if (tokenType) out.token_type = tokenType;
|
|
const scope = stringField(obj, "scope");
|
|
if (scope) out.scope = scope;
|
|
|
|
const expiresIn = numericField(obj, "expires_in");
|
|
if (expiresIn !== undefined) {
|
|
// Clamp to a sensible minimum so a misbehaving / clock-skewed
|
|
// server returning 0 or a negative value doesn't put expires_at in
|
|
// the past and cause the 401-refresh path to loop.
|
|
const clamped = Math.max(expiresIn, MIN_EXPIRES_IN_SECONDS);
|
|
out.expires_at = new Date(Date.now() + clamped * 1000).toISOString();
|
|
}
|
|
return out;
|
|
}
|
|
|
|
function stringField(obj: Record<string, unknown>, key: string): string | undefined {
|
|
const v = obj[key];
|
|
return typeof v === "string" && v.length > 0 ? v : undefined;
|
|
}
|
|
|
|
function numericField(obj: Record<string, unknown>, key: string): number | undefined {
|
|
const v = obj[key];
|
|
if (typeof v === "number" && Number.isFinite(v)) return v;
|
|
if (typeof v === "string") {
|
|
const n = Number.parseFloat(v);
|
|
return Number.isFinite(n) ? n : undefined;
|
|
}
|
|
return undefined;
|
|
}
|
|
|
|
/**
|
|
* Persist a new OAuth token set, always preserving a co-located `api_key`.
|
|
*
|
|
* `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.
|
|
* - 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. Throws `LOGIN_CHANGED`
|
|
* without writing if the stored login is no longer the refreshed one.
|
|
*/
|
|
async function persistOAuth(tokens: OAuthTokens, opts: { refreshed?: string } = {}): Promise<void> {
|
|
let existing: Credentials = {};
|
|
try {
|
|
const { credentials } = await readStore();
|
|
existing = credentials;
|
|
} catch (err) {
|
|
// A fresh login overwrites the OAuth block anyway; a refresh must not guess.
|
|
if (opts.refreshed !== undefined) throw err;
|
|
}
|
|
|
|
if (opts.refreshed !== undefined && existing.oauth?.refresh_token !== opts.refreshed) {
|
|
throw ErrLoginChanged();
|
|
}
|
|
const oauth: OAuthTokens =
|
|
opts.refreshed !== undefined
|
|
? { ...existing.oauth, ...tokens, ...oauthIdentity() }
|
|
: { ...tokens, ...oauthIdentity() };
|
|
// 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).
|
|
// Only the `oauth` block is overwritten here.
|
|
await writeStore({ ...existing, oauth });
|
|
}
|
|
|
|
/** Persist a verified fresh OAuth login while preserving cross-CLI fields. */
|
|
export async function persistFreshOAuth(tokens: OAuthTokens): Promise<void> {
|
|
await persistOAuth(tokens);
|
|
}
|
|
|
|
/**
|
|
* Atomically install a verified device session and its identity metadata.
|
|
*
|
|
* This is intentionally one credential-file rename: if the write fails, the
|
|
* previous credential remains intact and the caller can revoke the freshly
|
|
* minted tokens without leaving a half-installed session or stale identity.
|
|
*/
|
|
export async function persistVerifiedOAuthSession(
|
|
tokens: OAuthTokens,
|
|
user: StoredUserInfo,
|
|
): Promise<void> {
|
|
let credentials: Credentials = {};
|
|
try {
|
|
({ credentials } = await readStore());
|
|
} catch {
|
|
// Match the other fresh-login path: a corrupt prior file must not prevent
|
|
// installing a newly verified session.
|
|
credentials = {};
|
|
}
|
|
const next: Credentials = {
|
|
...credentials,
|
|
oauth: { ...tokens, ...oauthIdentity() },
|
|
};
|
|
if (user.email || user.first_name || user.last_name || user.username) {
|
|
// Preserve only unknown/foreign user fields from the existing record.
|
|
// Assigning every known field (including undefined) prevents identity
|
|
// fields from the previous account surviving when the new response omits
|
|
// them; serializeUser skips undefined values.
|
|
next.user = {
|
|
...credentials.user,
|
|
email: user.email,
|
|
first_name: user.first_name,
|
|
last_name: user.last_name,
|
|
username: user.username,
|
|
};
|
|
} else {
|
|
delete next.user;
|
|
}
|
|
await writeStore(next);
|
|
}
|
|
|
|
interface ParsedDeviceAuthorization {
|
|
deviceCode: string;
|
|
userCode: string;
|
|
verificationUri: string;
|
|
verificationUriComplete?: string;
|
|
expiresIn: number;
|
|
interval: number;
|
|
}
|
|
|
|
function parseDeviceAuthorizationResponse(payload: unknown): ParsedDeviceAuthorization {
|
|
const data = requireDeviceAuthorizationRecord(payload);
|
|
const deviceCode = stringField(data, "device_code");
|
|
const userCode = stringField(data, "user_code");
|
|
const verificationUri = requiredSafeVerificationUri(data, "verification_uri");
|
|
const verificationUriComplete = optionalSafeVerificationUri(data, "verification_uri_complete");
|
|
const expiresIn = strictNumericField(data, "expires_in");
|
|
const interval = strictNumericField(data, "interval");
|
|
requireSafeDeviceCode(deviceCode);
|
|
requireSafeDeviceCode(userCode);
|
|
const timing = normalizeDeviceAuthorizationTiming(data, expiresIn, interval);
|
|
return {
|
|
deviceCode,
|
|
userCode,
|
|
verificationUri,
|
|
...(verificationUriComplete ? { verificationUriComplete } : {}),
|
|
...timing,
|
|
};
|
|
}
|
|
|
|
function requireSafeDeviceCode(value: string | undefined): asserts value is string {
|
|
if (!value || !isHeaderSafe(value)) {
|
|
throw ErrDeviceAuthFailed("authorization server returned an invalid response");
|
|
}
|
|
}
|
|
|
|
function normalizeDeviceAuthorizationTiming(
|
|
data: Record<string, unknown>,
|
|
expiresIn: number | undefined,
|
|
interval: number | undefined,
|
|
): Pick<ParsedDeviceAuthorization, "expiresIn" | "interval"> {
|
|
if (
|
|
!isPositiveNumber(expiresIn) ||
|
|
(data["interval"] !== undefined && !isPositiveNumber(interval))
|
|
) {
|
|
throw ErrDeviceAuthFailed("authorization server returned invalid timing values");
|
|
}
|
|
return {
|
|
expiresIn,
|
|
interval: Math.min(
|
|
Math.max(Math.ceil(interval ?? MIN_DEVICE_POLL_SECONDS), MIN_DEVICE_POLL_SECONDS),
|
|
MAX_DEVICE_POLL_SECONDS,
|
|
),
|
|
};
|
|
}
|
|
|
|
function requiredSafeVerificationUri(data: Record<string, unknown>, key: string): string {
|
|
const value = normalizeSafeVerificationUri(stringField(data, key));
|
|
if (!value) throw ErrDeviceAuthFailed("authorization server returned an unsafe verification URL");
|
|
return value;
|
|
}
|
|
|
|
function optionalSafeVerificationUri(
|
|
data: Record<string, unknown>,
|
|
key: string,
|
|
): string | undefined {
|
|
if (data[key] === undefined) return undefined;
|
|
return requiredSafeVerificationUri(data, key);
|
|
}
|
|
|
|
function requireDeviceAuthorizationRecord(payload: unknown): Record<string, unknown> {
|
|
if (!payload || typeof payload !== "object" || Array.isArray(payload)) {
|
|
throw ErrDeviceAuthFailed("authorization server returned an invalid response");
|
|
}
|
|
return payload as Record<string, unknown>;
|
|
}
|
|
|
|
function isPositiveNumber(value: number | undefined): value is number {
|
|
return value !== undefined && value > 0;
|
|
}
|
|
|
|
function normalizeSafeVerificationUri(value: string | undefined): string | undefined {
|
|
if (!value || !isHeaderSafe(value)) return undefined;
|
|
try {
|
|
const url = new URL(value);
|
|
if (url.username || url.password) return undefined;
|
|
const allowed =
|
|
url.protocol === "https:" ||
|
|
(url.protocol === "http:" && ["127.0.0.1", "localhost"].includes(url.hostname));
|
|
return allowed ? url.href : undefined;
|
|
} catch {
|
|
return undefined;
|
|
}
|
|
}
|
|
|
|
async function readJsonOrDeviceError(res: Response): Promise<unknown> {
|
|
return await readBoundedDeviceJson(res);
|
|
}
|
|
|
|
async function readDeviceOAuthError(res: Response): Promise<string | undefined> {
|
|
try {
|
|
const payload = await readBoundedDeviceJson(res);
|
|
if (!payload || typeof payload !== "object" || Array.isArray(payload)) return undefined;
|
|
const error = (payload as Record<string, unknown>)["error"];
|
|
return typeof error === "string" ? error : undefined;
|
|
} catch {
|
|
return undefined;
|
|
}
|
|
}
|
|
|
|
function strictNumericField(obj: Record<string, unknown>, key: string): number | undefined {
|
|
const value = obj[key];
|
|
if (typeof value === "number") return Number.isFinite(value) ? value : undefined;
|
|
if (typeof value !== "string" || value.trim() === "") return undefined;
|
|
const parsed = Number(value);
|
|
return Number.isFinite(parsed) ? parsed : undefined;
|
|
}
|
|
|
|
async function readBoundedDeviceJson(res: Response): Promise<unknown> {
|
|
if (!res.body) throw ErrDeviceAuthFailed("authorization server returned no data");
|
|
const reader = res.body.getReader();
|
|
const chunks: Uint8Array[] = [];
|
|
let total = 0;
|
|
try {
|
|
while (true) {
|
|
const { done, value } = await reader.read();
|
|
if (done) break;
|
|
if (!value) continue;
|
|
total += value.byteLength;
|
|
if (total > MAX_DEVICE_RESPONSE_BYTES) {
|
|
await reader.cancel();
|
|
throw ErrDeviceAuthFailed("authorization server response was too large");
|
|
}
|
|
chunks.push(value);
|
|
}
|
|
const body = new Uint8Array(total);
|
|
let offset = 0;
|
|
for (const chunk of chunks) {
|
|
body.set(chunk, offset);
|
|
offset += chunk.byteLength;
|
|
}
|
|
return JSON.parse(new TextDecoder().decode(body));
|
|
} catch (err) {
|
|
if (isAuthError(err)) throw err;
|
|
throw ErrDeviceAuthFailed("authorization server returned non-JSON data");
|
|
} finally {
|
|
reader.releaseLock();
|
|
}
|
|
}
|
|
|
|
async function readJsonOrThrow(res: Response): Promise<unknown> {
|
|
try {
|
|
return await res.json();
|
|
} catch (err) {
|
|
throw ErrApi(res.status, `non-JSON body: ${(err as Error).message}`);
|
|
}
|
|
}
|
|
|
|
async function safeText(res: Response): Promise<string> {
|
|
try {
|
|
// Token/revoke requests carry refresh_token, authorization code, and
|
|
// code_verifier in the form body; a server/proxy error page can echo
|
|
// request data back. Scrub before the text reaches any error message.
|
|
return scrubCredentials((await res.text()).slice(0, 500));
|
|
} catch {
|
|
return "";
|
|
}
|
|
}
|