/** * @module * * Core abstractions shared by all OAuth 2.0 grant type flow implementations. * * Defines the base {@link OAuth2Flow} class, shared option/model interfaces, * and the function signature types used by the pluggable model layer. */ import { OAuth2Error } from "../errors.js"; import { TokenType, TokenTypeValidationResponse } from "../token_types/types.js"; import { ClientAuthMethod, TokenEndpointAuthMethod } from "../client_auth_methods/mod.js"; import { OAuth2Client, OAuth2TokenResponseBody } from "../types.js"; import { StrategyOptions, StrategyResult } from "../strategy.js"; /** * The discriminated union returned by a flow's `token()` method. * * - On success: contains the token response body and the grant type that produced it. * - On failure: contains the OAuth2 error to return to the client. */ export type OAuth2FlowTokenResponse = { success: true; tokenResponse: OAuth2TokenResponseBody; grantType: string; } | { success: false; error: OAuth2Error; }; /** * Strategy options passed to the token verification layer. * Mirrors {@link StrategyOptions} but omits `tokenType`, which is managed by the flow. */ export interface OAuth2FlowStrategyOptions extends Omit { } /** * Base configuration options shared by all OAuth 2.0 flow implementations. */ export interface OAuth2FlowOptions { /** * Options forwarded to the token verification strategy (e.g. the `verifyToken` handler). */ strategyOptions: OAuth2FlowStrategyOptions; /** * The OpenAPI security scheme name for this flow. * Used as the key in `toOpenAPISecurityScheme()` and `toOpenAPIPathItem()`. * @default "oauth2-flow" */ securitySchemeName?: string; /** * The default lifetime in seconds for issued access tokens. * @default 3600 */ accessTokenLifetime?: number; /** * The URL of the token endpoint. Used in OpenAPI security scheme generation. * @default "/token" */ tokenEndpoint?: string; /** * The token type implementation to use for this flow (e.g. Bearer, DPoP). * Defaults to {@link BearerTokenType}. */ tokenType?: TokenType; /** * A human-readable description for the OpenAPI security scheme. */ description?: string; /** * A map of scope names to their descriptions, used in OpenAPI security scheme generation. */ scopes?: Record; /** * The client authentication methods to register on this flow. * Accepts method identifier strings or custom {@link ClientAuthMethod} instances. * Defaults to `client_secret_basic` if none are provided. */ clientAuthenticationMethods?: (ClientAuthMethod | "client_secret_basic" | "client_secret_post" | "none")[]; } /** * The base shape of a successful access token result returned by `generateAccessToken()`. */ export interface OAuth2AccessTokenResult { type?: "access_token"; accessToken: string; } /** * Returned by `generateAccessToken()` to signal a domain-level error * (e.g. `authorization_pending` in the device code flow) without throwing. * * The flow's `token()` method maps these to the appropriate OAuth 2.0 error responses. */ export interface OAuth2AccessTokenError { /** Discriminator. Always `"error"`. */ type: "error"; /** The OAuth 2.0 error code (e.g. `"authorization_pending"`, `"access_denied"`). */ error: string; /** A human-readable description of the error. */ errorDescription?: string; /** A URI pointing to a page with more information about the error. */ errorUri?: string; } /** * Validation context passed to `generateAccessTokenFromRefreshToken()` when * handling a `refresh_token` grant request. */ export interface OAuth2RefreshTokenGrantContext { /** The grant type identifier. Always `"refresh_token"`. */ grantType: "refresh_token"; /** The authenticated client presenting the refresh token. */ client: OAuth2Client; /** The token type prefix (e.g. `"Bearer"`, `"DPoP"`). */ tokenType: string; /** The access token lifetime in seconds. */ accessTokenLifetime: number; /** The refresh token string from the request. */ refreshToken: string; /** The origin of the request, used for validation and security purposes. */ origin: string; /** The result of the token type validation. */ tokenTypeValidation: TokenTypeValidationResponse; /** The requested scopes for the new access token, if provided. */ scope?: string[]; } /** * Raw refresh token request parameters for refresh token grant. */ export interface OAuth2RefreshTokenRequest { /** The grant type value. Always `"refresh_token"`. */ grantType: "refresh_token"; /** The client identifier. */ clientId: string; /** The refresh token string from the request. */ refreshToken: string; /** The origin of the request, used for validation and security purposes. */ origin: string; /** The result of the token type validation. */ tokenTypeValidation: TokenTypeValidationResponse; /** The client authentication method used for this request, if any. */ clientAuthMethod?: string | undefined; /** The client authentication data extracted from the request, if any. */ clientAuthData?: Partial | undefined; /** The client secret, if the client is confidential. */ clientSecret?: string; /** The requested scopes for the new access token, if provided. */ scope?: string[]; } /** * A function that retrieves a registered OAuth 2.0 client from the application's store. * * @template TRequestInfo - The shape of the token or authorization request object. * * @param requestInfo - The parsed request parameters. * @returns The matching client, or `undefined` if not found or authentication fails. */ export interface OAuth2GetClientFunction { (requestInfo: TRequestInfo): Promise | OAuth2Client | undefined; } /** * A function that generates an access token for an authenticated grant context. * * @template TGrantContext - The grant-specific context object (client, scopes, lifetime, etc.). * @template TAccessToken - The shape of the token result (string, result object, or error object). * * @param context - The validated grant context. * @returns The generated token, an error result, or `undefined` on failure. */ export interface OAuth2GenerateAccessTokenFunction { (context: TGrantContext): Promise | TAccessToken | undefined; } /** * A function that generates a new access token from an existing refresh token. * * @template TAccessToken - The shape of the token result (string, result object, or error object). * * @param context - The refresh token grant context. * @returns The generated token, an error result, or `undefined` on failure. */ export interface OAuth2GenerateAccessTokenFromRefreshTokenFunction { (context: OAuth2RefreshTokenGrantContext): Promise | TAccessToken | undefined; } /** * The pluggable model interface that grant flow implementations delegate to * for client lookup and token generation. * * @template TTokenRequest - The shape of the token endpoint request parameters. * @template TGrantContext - The grant-specific context object passed to token generation. * @template TAccessToken - The shape of the token result. Defaults to `OAuth2AccessTokenResult | string`. */ export interface OAuth2GrantModel { /** * Retrieve a client by its id and optionally verify its secret. */ getClient: OAuth2GetClientFunction; /** * Generate an access token for the grant type. */ generateAccessToken: OAuth2GenerateAccessTokenFunction; /** * Generate a new access token from a refresh token. * Optional - only implement if the flow supports refresh token grants. */ generateAccessTokenFromRefreshToken?: OAuth2GenerateAccessTokenFromRefreshTokenFunction; } /** * Abstract base class for all OAuth 2.0 grant type flow implementations. * * Manages client authentication method registration, token type configuration, * access token lifetime, and token verification. Subclasses implement `token()` * and `toOpenAPISecurityScheme()` for their specific grant type. */ export declare abstract class OAuth2Flow { /** The grant type identifier for this flow (e.g. `"client_credentials"`). */ abstract readonly grantType: string; protected readonly strategyOptions: OAuth2FlowStrategyOptions; protected _clientAuthMethods: Record; protected _tokenType: TokenType; /** * The token type prefix used in the `Authorization` header (e.g. `"Bearer"`, `"DPoP"`). * Derived from the configured {@link TokenType}. */ get tokenType(): string; protected get clientAuthMethods(): Record; protected securitySchemeName: string; /** Default lifetime (in seconds) for access tokens. @default {3600} */ protected accessTokenLifetime: number; protected tokenEndpoint: string; protected description?: string; protected scopes?: Record; constructor(options?: OAuth2FlowOptions); protected extractClientCredentials(req: Request, authMethodsInstances: Record, supported: TokenEndpointAuthMethod[]): Promise<{ clientId?: string; clientSecret?: string; error?: OAuth2Error; method?: TokenEndpointAuthMethod; clientAuthData?: Partial; }>; protected addClientAuthenticationMethod(value: "client_secret_basic" | "client_secret_post" | "none" | ClientAuthMethod): this; /** * Returns the list of active client authentication method identifiers for this flow, * sorted in the standard preference order. * Defaults to `["client_secret_basic"]` if no methods have been registered. */ getTokenEndpointAuthMethods(): TokenEndpointAuthMethod[]; /** * Sets the default access token lifetime for this flow. * * @param ttlSeconds - Lifetime in seconds of the access token. Defaults to 1 hour. */ setAccessTokenLifetime(ttlSeconds?: number): this; /** * Returns the configured access token lifetime in seconds. */ getAccessTokenLifetime(): number | undefined; /** * Sets the human-readable description for the OpenAPI security scheme. * * @param description - A short description of this flow. */ setDescription(description: string): this; /** * Sets the scopes advertised by this flow in the OpenAPI security scheme. * * @param scopes - A map between scope names and short descriptions. * The map MAY be empty. */ setScopes(scopes: Record): this; /** * Sets the token endpoint URL used in OpenAPI security scheme generation. * * @param tokenEndpoint - The token endpoint URL (absolute or relative). */ setTokenEndpoint(tokenEndpoint: string): this; /** * Returns the configured token endpoint URL. */ getTokenEndpoint(): string; /** * Returns the configured scopes map, or `undefined` if none have been set. */ getScopes(): Record | undefined; /** * Returns the OpenAPI security scheme name for this flow. */ getSecuritySchemeName(): string; /** * Returns the human-readable description for the OpenAPI security scheme, if set. */ getDescription(): string | undefined; /** * Verifies that the token in the request grants access to a protected resource. * Delegates to the configured `verifyToken` strategy handler. * * @param request - The incoming HTTP request containing the `Authorization` header. * @returns The strategy result - success with credentials, or a typed failure. */ verifyToken(request: Request): Promise; /** * Returns the OpenAPI path item security requirement object for this flow. * * @param scopes - Optional list of required scopes for the path item. * @returns An object keyed by the security scheme name with the required scopes. */ toOpenAPIPathItem(scopes?: string[]): Record; /** * Handle a token request for the specific grant type. * * @param request - The incoming HTTP request to the token endpoint. * @returns The token response - success with the token body, or failure with an error. */ abstract token(request: Request): Promise; /** * Returns the OpenAPI security scheme definition for this flow. * The returned object is keyed by the security scheme name. */ abstract toOpenAPISecurityScheme(): Record; } //# sourceMappingURL=flow.d.ts.map