import { type AsyncValueCache, type Getter, type Maybe, type Milliseconds, type OidcTokenResponse, type UnixDateTimeMillisecondsNumber } from '@dereekb/util'; /** * Default pre-emptive refresh buffer in milliseconds. * * An access token is treated as needing a refresh this far ahead of its real expiry to absorb * clock skew and request latency. */ export declare const DEFAULT_OIDC_TOKEN_REFRESH_BUFFER_MS = 60000; /** * Environment-agnostic snapshot of an OIDC relying party's current tokens. * * Persisted via an {@link OidcTokenStorage}. `expiresAt` is stored as an absolute unix epoch * milliseconds value (rather than a `Date`) so the state round-trips cleanly through JSON storage * such as `localStorage`. */ export interface OidcTokenState { readonly accessToken: string; readonly refreshToken?: Maybe; readonly idToken?: Maybe; readonly tokenType?: Maybe; readonly scope?: Maybe; /** * Absolute access-token expiry as unix epoch milliseconds. Absent ⇒ unknown (treated as expired). */ readonly expiresAt?: Maybe; /** * Optional decoded identity claims (e.g. from the `id_token`), surfaced to UIs. */ readonly claims?: Maybe>; } /** * Single-value async cache holding the current {@link OidcTokenState}. * * Defaults to {@link inMemoryAsyncValueCache}; environment shells supply a persistent backing * (e.g. a `localStorage`-backed cache in the browser, a file-backed cache in a CLI). */ export type OidcTokenStorage = AsyncValueCache; export interface OidcTokenStateFromResponseConfig { /** * The current time used to anchor `expires_in`. Defaults to the present time. */ readonly now?: Maybe; /** * Pre-decoded identity claims. When omitted, the claims are decoded from the response `id_token`. */ readonly claims?: Maybe>; } /** * Normalizes an {@link OidcTokenResponse} into an {@link OidcTokenState}, converting the relative * `expires_in` (seconds) into an absolute `expiresAt` (epoch ms) anchored at `config.now`. * * @param response - The token endpoint response to normalize. * @param config - Optional anchoring time and pre-decoded claims. * @returns The normalized {@link OidcTokenState}. */ export declare function oidcTokenStateFromResponse(response: OidcTokenResponse, config?: OidcTokenStateFromResponseConfig): OidcTokenState; /** * Returns true when the access token's real expiry has already passed (no buffer applied), or when * the state / its `expiresAt` is missing. * * @param state - The token state to inspect. * @param now - Optional current time override. * @returns Whether the access token has expired. */ export declare function isAccessTokenExpired(state: Maybe, now?: Maybe): boolean; /** * Returns true when the access token is expired or within `bufferMs` of expiry (pre-emptive * refresh), or when the state / its `expiresAt` is missing. * * @param state - The token state to inspect. * @param now - Optional current time override. * @param bufferMs - Pre-emptive refresh buffer in milliseconds. Defaults to {@link DEFAULT_OIDC_TOKEN_REFRESH_BUFFER_MS}. * @returns Whether the access token should be refreshed. */ export declare function accessTokenNeedsRefresh(state: Maybe, now?: Maybe, bufferMs?: number): boolean; /** * Returns the milliseconds remaining until the access token should be pre-emptively refreshed * (its real expiry minus `bufferMs`), clamped to a minimum of `0`. * * @param state - The token state to inspect. * @param now - Optional current time override. * @param bufferMs - Pre-emptive refresh buffer in milliseconds. Defaults to {@link DEFAULT_OIDC_TOKEN_REFRESH_BUFFER_MS}. * @returns The delay in milliseconds, or `0` when already due / unknown. */ export declare function nextRefreshDelay(state: Maybe, now?: Maybe, bufferMs?: number): number; /** * Performs a single refresh-token exchange and returns the new token response. * * Wired by the environment shell to call {@link refreshAccessToken} with the resolved endpoint + * client credentials + injected fetch. */ export type OidcTokenRefreshFunction = (input: OidcTokenRefreshFunctionInput) => Promise; export interface OidcTokenRefreshFunctionInput { /** * The current token state being refreshed. */ readonly state: OidcTokenState; /** * The refresh token to redeem (non-null — the manager only calls refresh when one is present). */ readonly refreshToken: string; } export interface OidcTokenManagerConfig { /** * Backing token store. Defaults to an in-memory cache. */ readonly storage?: OidcTokenStorage; /** * Refresh-token exchange function. Required. */ readonly refresh: OidcTokenRefreshFunction; /** * Current-time getter (epoch ms). Defaults to `Date.now`. */ readonly now?: Getter; /** * Pre-emptive refresh buffer in milliseconds. Defaults to {@link DEFAULT_OIDC_TOKEN_REFRESH_BUFFER_MS}. */ readonly refreshBufferMs?: number; } /** * The env-agnostic token "brain": resolves a valid access token, refreshing lazily and * de-duplicating concurrent refreshes into one network call. */ export interface OidcTokenManager { /** * Loads the stored state, returning a valid access token — refreshing first when the current one * is missing/expired. Resolves to `undefined` when there is no usable token (logged out, or the * refresh failed with `invalid_grant`, which also clears the store). */ getValidAccessToken(): Promise>; /** * Returns the currently stored token state. */ getState(): Promise>; /** * Replaces the stored token state (e.g. after an initial login exchange). */ setState(state: OidcTokenState): Promise; /** * Forces a refresh now (sharing any in-flight refresh), returning the new state. */ refreshNow(): Promise>; /** * Clears the stored token state (logout). */ clear(): Promise; } /** * Creates an {@link OidcTokenManager} over the given storage + refresh function. * * - **Lazy** — refreshes only on demand (no timer), so it works unchanged in a CLI or browser. * - **Single-flight** — concurrent `getValidAccessToken()` / `refreshNow()` calls share one * in-flight refresh, so N callers trigger at most one network exchange. * - **Rotation-safe** — a rotated `refresh_token` replaces the old one; when the response omits it, * the prior refresh token is kept. The `id_token`/`claims` are likewise carried forward when a * refresh response omits them. * - **invalid_grant → logout** — a refresh that fails with `TOKEN_INVALID_GRANT` clears the store * and surfaces as "no token" (`undefined`); other errors propagate. * * @param config - The manager configuration. * @returns The configured {@link OidcTokenManager}. */ export declare function oidcTokenManager(config: OidcTokenManagerConfig): OidcTokenManager; /** * Decodes the (unverified) payload claims from a JWT such as an `id_token`. * * This does NOT verify the signature — it is purely for surfacing identity claims a relying party * already trusts (the token was just issued to it). Returns `undefined` when the input is missing * or not a decodable JWT. * * @param token - The JWT string. * @returns The decoded claims object, or `undefined`. */ export declare function decodeJwtClaims(token: Maybe): Maybe>; /** * Default refresh skew: a cached token is re-minted once it is within this many milliseconds of * expiring. Wider than {@link DEFAULT_OIDC_TOKEN_REFRESH_BUFFER_MS} because a re-mint is a local * signing operation rather than a network exchange, so pre-empting early costs nothing. */ export declare const DEFAULT_CACHED_TOKEN_REFRESH_SKEW_MS: Milliseconds; /** * A minted token and when it expires. */ export interface MintedToken { readonly token: string; readonly expiresAt: Date; } /** * A `getToken` function that hands out the same minted token until it nears expiry. */ export type CachedTokenProvider = Getter>; export interface CachedTokenProviderConfig { /** * Mints a fresh token. */ readonly mint: Getter>; /** * Re-mint once `expiresAt - now` drops below this. Defaults to {@link DEFAULT_CACHED_TOKEN_REFRESH_SKEW_MS}. */ readonly refreshSkewMs?: Maybe; /** * Clock in epoch milliseconds; injected in specs. Defaults to `Date.now`. */ readonly now?: Maybe>; } /** * Wraps a token minter in a cache: the current token is reused until it is within * `refreshSkewMs` of expiring, then re-minted. Concurrent callers during a mint share the * single in-flight promise (single-flight), and a failed mint leaves nothing cached so the * next call retries. * * Adjacent to {@link oidcTokenManager}, not redundant with it: the manager redeems a **refresh * token** against a token endpoint, while this re-**mints** from scratch (e.g. an API signing a * first-party JWT for a resource it owns) and holds no refresh token at all. * * @param config - The minter, refresh skew, and clock. * @returns The caching token provider. */ export declare function createCachedTokenProvider(config: CachedTokenProviderConfig): CachedTokenProvider;