import { BaseError } from 'make-error'; import { type CodedError } from '../error/error'; import { type Maybe } from '../value/maybe.type'; /** * Standard "out-of-band" OAuth 2.0 redirect URI URN. * * Defined by RFC 6749 §1.3 / draft-ietf-oauth-native-apps. Used by native and CLI clients that * have no HTTP server to receive the redirect — the authorization server displays the * authorization code on a final page and the user pastes it back into the application. * * Many providers have deprecated this in favor of loopback redirects (e.g. * `http://127.0.0.1:/callback`), but it remains in use as a fallback for tools that cannot * bind a local port. */ export declare const OAUTH_OOB_REDIRECT_URI = "urn:ietf:wg:oauth:2.0:oob"; /** * Default OAuth scope requested by an OIDC relying party when no explicit scope list is provided. * * `openid` is the one scope every OpenID Connect flow must request to receive an ID token. */ export declare const DEFAULT_OIDC_RELYING_PARTY_SCOPE = "openid"; /** * Stable error code identifying a failure raised by the OIDC relying-party (token-consumer) layer. * * Shared by the pure helpers here and the network protocol functions in `@dereekb/util/oidc`. * Consumers (CLI, browser) re-wrap or branch on these codes at their boundary. */ export type OidcRelyingPartyErrorCode = 'DISCOVERY_FAILED' | 'TOKEN_EXCHANGE_FAILED' | 'TOKEN_INVALID_GRANT' | 'TOKEN_REVOCATION_FAILED' | 'USERINFO_FAILED' | 'SESSION_INFO_FAILED' | 'AUTH_NO_CODE' | 'AUTH_PROVIDER_ERROR' | 'AUTH_REDIRECT_PARSE_FAILED' | 'INVALID_STATE' | 'INVALID_SESSION_TTL'; export interface OidcRelyingPartyErrorInput { readonly message: string; readonly code: OidcRelyingPartyErrorCode; /** * The original error, if this error wraps one. */ readonly _error?: unknown; } /** * Error raised by the OIDC relying-party layer (pure helpers here + the network protocol functions * in `@dereekb/util/oidc`). Carries a stable {@link OidcRelyingPartyErrorCode} so environment shells * (CLI, browser) can branch on or re-wrap it without string-matching messages. */ export declare class OidcRelyingPartyError extends BaseError implements CodedError { readonly code: OidcRelyingPartyErrorCode; readonly _error?: unknown; constructor(input: OidcRelyingPartyErrorInput); } /** * The subset of fields read from an OIDC discovery document. * * A relying party uses the authorization, token, userinfo, and revocation endpoints to drive * the authorization-code-with-PKCE flow. */ export interface OidcDiscoveryMetadata { readonly issuer: string; readonly authorization_endpoint: string; readonly token_endpoint: string; readonly userinfo_endpoint?: string; readonly revocation_endpoint?: string; readonly end_session_endpoint?: string; readonly jwks_uri?: string; readonly scopes_supported?: string[]; } /** * Token response from a successful `authorization_code` or `refresh_token` exchange. */ export interface OidcTokenResponse { readonly access_token: string; readonly token_type?: string; readonly expires_in?: number; readonly refresh_token?: string; readonly id_token?: string; readonly scope?: string; } /** * Session lifetime metadata returned by the dbx-components `GET /oidc/session` route. */ export interface OidcSessionInfo { readonly sub?: string; readonly scope?: Maybe; /** * Grant (session) expiry as unix epoch SECONDS, or `null` when the provider could not resolve it. */ readonly expiresAt?: Maybe; /** * Whether refresh-token rotation is disabled for this grant (a long-lived service token). */ readonly rotationDisabled?: boolean; } /** * How a confidential OAuth client authenticates itself at the token and revocation endpoints. * * - `client_secret_post` — credentials in the form body. * - `client_secret_basic` — credentials in an HTTP Basic `Authorization` header. This is the OIDC * Discovery *specification* default when a provider omits `token_endpoint_auth_methods_supported`, * and is what Discord requires. * * A provider accepting both is unaffected by the choice; one accepting only Basic (Discord) rejects * the body form outright, which is why this is configurable rather than fixed. */ export type OidcClientAuthMethod = 'client_secret_post' | 'client_secret_basic'; /** * The {@link OidcClientAuthMethod} used when a request does not name one. * * `client_secret_post` rather than the spec's `client_secret_basic`, because every relying-party * call in this workspace predates the option and posted its secret in the body. */ export declare const DEFAULT_OIDC_CLIENT_AUTH_METHOD: OidcClientAuthMethod; /** * The client credentials + auth method mixed into every token/revocation endpoint request. */ export interface OidcClientAuthInput { readonly clientId: string; /** * Optional client secret. A confidential client presents it via the configured * {@link OidcClientAuthMethod}; a public PKCE client (`token_endpoint_auth_method: 'none'`) omits * it and authenticates via the `code_verifier` alone. */ readonly clientSecret?: Maybe; /** * How the client credentials are presented. Defaults to {@link DEFAULT_OIDC_CLIENT_AUTH_METHOD}. * * Ignored when no `clientSecret` is set — a public client has nothing to present. */ readonly clientAuth?: Maybe; } export interface OidcClientSecretBasicAuthorizationHeaderInput { readonly clientId: string; readonly clientSecret: string; } /** * Builds the HTTP Basic `Authorization` header value authenticating an OAuth client via * `client_secret_basic`. * * Uses `btoa()` rather than `Buffer`, so this stays usable outside Node — the same choice the PKCE * helpers make. * * @param input - The client credentials to encode. * @param input.clientId - The OAuth client id. * @param input.clientSecret - The OAuth client secret. * @returns The `Authorization` header value, including the `Basic ` prefix. * * @__NO_SIDE_EFFECTS__ */ export declare function oidcClientSecretBasicAuthorizationHeader(input: OidcClientSecretBasicAuthorizationHeaderInput): string; export interface DiscoverOidcMetadataInput { readonly issuer: string; /** * Optional sibling base URL to try after the issuer-prefixed and origin-rooted paths. * * Useful when the discovery doc is served at `/.well-known/openid-configuration` * — e.g. when the issuer is reached via a different host than the API and the origin-rooted * candidate would target the wrong host. */ readonly fallbackBaseUrl?: string | undefined; } export interface ExchangeAuthorizationCodeInput extends OidcClientAuthInput { readonly tokenEndpoint: string; readonly redirectUri: string; readonly code: string; /** * The PKCE code verifier originally paired with the code challenge. * * Optional: a confidential client that did NOT send a `code_challenge` on the authorization * request must omit it, since a provider rejects a `code_verifier` for a code minted without a * challenge. Always set it when the authorization request carried a challenge. */ readonly codeVerifier?: Maybe; } export interface RefreshAccessTokenInput extends OidcClientAuthInput { readonly tokenEndpoint: string; readonly refreshToken: string; } export interface RevokeTokenInput extends OidcClientAuthInput { readonly revocationEndpoint: string; readonly token: string; readonly tokenTypeHint?: 'access_token' | 'refresh_token' | undefined; } export interface FetchUserInfoInput { readonly userinfoEndpoint: string; readonly accessToken: string; } export interface FetchSessionInfoInput { /** * The `GET /oidc/session` endpoint URL (typically `/session`). */ readonly sessionEndpoint: string; readonly accessToken: string; } /** * Builds the ordered list of `.well-known/openid-configuration` URLs probed when discovering OIDC * metadata. * * 1. `/.well-known/openid-configuration` (OpenID Connect Discovery 1.0). * 2. `/.well-known/openid-configuration` (host-rooted; matches projects that * mount the discovery controller at the API/dev-server root rather than under the issuer * sub-path — e.g. demo's `OidcWellKnownController`). * 3. `/.well-known/openid-configuration` when supplied and not already covered. * * Exported so diagnostic surfaces (e.g. a CLI `doctor`) can show the exact URLs the discovery step * tried — without re-implementing the candidate ordering. * * @param input - The discovery request. * @param input.issuer - The OIDC issuer URL whose `.well-known/openid-configuration` is fetched first. * @param input.fallbackBaseUrl - Optional sibling base URL appended after the issuer-prefixed and origin-rooted candidates. * @returns The candidate URL list in probe order, de-duplicated. * * @__NO_SIDE_EFFECTS__ */ export declare function buildOidcDiscoveryCandidates(input: DiscoverOidcMetadataInput): string[]; /** * Returns the input URL string with a single trailing slash removed, if present. * * @param url - The URL string to trim. * @returns The URL without a trailing slash. * * @__NO_SIDE_EFFECTS__ */ export declare function trimSlash(url: string): string; export interface BuildAuthorizationUrlInput { readonly authorizationEndpoint: string; /** * Optional OIDC issuer URL (e.g. `https://api.example.com/oidc`). Used as a fallback rebase * origin when `appClientUrl` is not provided — the origin of `oidcIssuer` is applied to the * discovered `authorizationEndpoint`. In typical OIDC deployments the issuer and authorization * endpoint share an origin, so this fallback is a no-op rebase that ends up at the discovered * `/oidc/auth` URL. Use `appClientUrl` to send the user to a different origin (e.g. a frontend * dev server that proxies `/oidc/**` back to the API). */ readonly oidcIssuer?: Maybe; /** * Optional API base URL. Used as a fallback rebase origin when neither `appClientUrl` nor * `oidcIssuer` is provided — only the origin is read, so prefix paths like `/api` are ignored. * Prefer `oidcIssuer` for new deployments; `apiBaseUrl` is kept for backwards compatibility * with envs that only declare an API base URL. */ readonly apiBaseUrl?: Maybe; /** * Optional client origin to rebase the authorization endpoint onto. * * When set, the path + search of `authorizationEndpoint` are kept and the origin is replaced * with this URL. Takes precedence over both `oidcIssuer` and `apiBaseUrl`. Recommended for any * env where the user-facing URL should differ from the discovered authorization endpoint — * e.g. a frontend dev server that proxies `/oidc/**` to the API on another port. When omitted, * the URL is derived from `oidcIssuer`/`apiBaseUrl` origin (or used verbatim if neither is set), * so the relying party always opens the actual authorization endpoint (typically `/oidc/auth`). */ readonly appClientUrl?: Maybe; readonly clientId: string; readonly redirectUri: string; /** * Space-separated scope list. Defaults to {@link DEFAULT_OIDC_RELYING_PARTY_SCOPE}. */ readonly scopes?: string | undefined; readonly state: string; readonly codeChallenge: string; /** * Optional requested login duration in seconds. When set, the URL includes the * `dbx_session_ttl=` query param so the OIDC server applies the requested * lifetime to the issued Session, Grant, and RefreshToken (subject to per-client and * server caps). */ readonly requestedSessionTtlSeconds?: Maybe; } /** * Builds the authorization URL the user opens in a browser to start the PKCE flow. * * The user-facing endpoint is the discovered `authorizationEndpoint` (typically `/oidc/auth`) * with its origin optionally rebased. The rebase origin is the first non-empty value among * `appClientUrl` → `oidcIssuer` origin → `apiBaseUrl` origin. In a typical single-host * deployment all three resolve to the same origin and the rebase is a no-op; in a split-host * setup (frontend dev server proxying `/oidc/**` to the API) `appClientUrl` redirects the user * through the frontend. When none of the three is provided, the discovered endpoint is used * unchanged. * * Always lands at the actual authorization endpoint so oidc-provider can create an interaction * and redirect to the app login page with a `uid`. * * @param input - The authorization URL inputs. * @param input.authorizationEndpoint - The authorization endpoint discovered from OIDC metadata. * @param input.appClientUrl - Optional client origin to rebase the authorization endpoint onto. Takes precedence over `oidcIssuer` and `apiBaseUrl`. * @param input.oidcIssuer - Optional OIDC issuer URL; falls back to its origin as the rebase target when `appClientUrl` is missing. * @param input.apiBaseUrl - Optional API base URL; falls back to its origin as the rebase target when neither `appClientUrl` nor `oidcIssuer` is set. * @param input.clientId - The OAuth client ID. * @param input.redirectUri - The redirect URI registered with the OAuth client. * @param input.scopes - Space-separated scope list. Defaults to {@link DEFAULT_OIDC_RELYING_PARTY_SCOPE}. * @param input.state - The opaque OAuth state token used for CSRF protection. * @param input.codeChallenge - The PKCE code challenge derived from the verifier. * @returns The full authorization URL with all OAuth params merged in. * @throws {OidcRelyingPartyError} When `requestedSessionTtlSeconds` is provided but is not a positive integer. * * @__NO_SIDE_EFFECTS__ */ export declare function buildAuthorizationUrl(input: BuildAuthorizationUrlInput): string; export interface PkceMaterial { readonly codeVerifier: string; readonly codeChallenge: string; } /** * Generates a fresh PKCE code verifier and the matching SHA-256 code challenge. * * @returns A {@link PkceMaterial} pair consisting of the random `codeVerifier` and its derived `codeChallenge`. */ export declare function generatePkceMaterial(): Promise; /** * Generates a random URL-safe state value for the OAuth state parameter. * * @returns A 32-character hex string derived from 16 random bytes. */ export declare function generateOAuthState(): string; export interface ParseAuthorizationRedirectInput { /** * The redirect URL (e.g. `window.location.href`) or a bare authorization code. */ readonly url: string; /** * Optional state value to assert against the redirect's `state` when present. */ readonly expectedState?: string | undefined; } export interface ParsedAuthorizationRedirect { readonly code: string; readonly state?: string | undefined; } /** * Parses an authorization code out of a redirect URL or a bare code string. * * Validates the `state` parameter when an expected value is provided. * * @param input - The parse inputs. * @param input.url - The redirect URL or bare authorization code. * @param input.expectedState - Optional state value to assert against `state` when present in the URL. * @returns The {@link ParsedAuthorizationRedirect} containing `code` and (when present) `state`. * @throws {OidcRelyingPartyError} When `url` is empty, when the URL contains no `code` parameter, or when `expectedState` does not match the URL's `state`. */ export declare function parseAuthorizationRedirect(input: ParseAuthorizationRedirectInput): ParsedAuthorizationRedirect;