UNPKG

@oa2/core

Version:

A comprehensive, RFC-compliant OAuth 2.0 authorization server implementation in TypeScript

1 lines 15.4 kB
{"version":3,"file":"types.d.ts","sources":["../src/types.ts"],"sourcesContent":["/**\n * Export a type that list the posible error coes\n */\nexport type OAuth2ErrorCode =\n | 'invalid_request'\n | 'unauthorized_client'\n | 'access_denied'\n | 'unsupported_response_type'\n | 'invalid_scope'\n | 'server_error'\n | 'temporarily_unavailable'\n | 'invalid_grant'\n | 'unsupported_grant_type';\n\n/**\n * Represents an incoming OAuth2 request, abstracting away framework-specific details.\n * @see RFC 6749, Section 3.1 Authorization Endpoint\n * @see RFC 6749, Section 3.2 Token Endpoint\n */\nexport interface OAuth2Request {\n /** The path of the request (e.g., '/token'). */\n path: string;\n\n /** The HTTP method of the request (GET or POST). */\n method: 'GET' | 'POST';\n\n /** A record of request headers. */\n headers: Record<string, string>;\n\n /** A record of query parameters. */\n query: Record<string, string>;\n\n /** The request body, parsed as a record of any type. */\n body?: Record<string, any> | string;\n\n /** A record of request cookies. */\n cookies: Record<string, string>;\n}\n\n/**\n * Represents an outgoing OAuth2 response, abstracting away framework-specific details.\n * @see RFC 6749, Section 3.1.2 Redirection Endpoint\n * @see RFC 6749, Section 4.1.4 Access Token Response\n * @see RFC 6749, Section 5.1 Successful Response\n * @see RFC 6749, Section 5.2 Error Response\n */\nexport interface OAuth2Response {\n /** The HTTP status code of the response. */\n statusCode: number;\n\n /** A record of response headers. */\n headers: Record<string, string>;\n\n /** The response body, which can be a record of any type. */\n body: Record<string, any>;\n\n /** Optional: A URL to redirect to, if the response is a redirect. */\n redirect?: string;\n\n /** A record of response cookies. */\n cookies: Record<string, string>;\n}\n\n/**\n * Represents an OAuth2 client application.\n * @see RFC 6749, Section 2. Client Registration\n * @see RFC 6749, Section 2.1 Client Types\n * @see RFC 6749, Section 2.2 Client Identifier\n * @see RFC 6749, Section 2.3 Client Authentication\n */\nexport interface Client {\n /** The unique identifier for the client. */\n id: string;\n\n /** The client secret, hashed for confidential clients. */\n secret: string;\n\n /** An array of registered redirect URIs for the client. */\n redirectUris: string[];\n\n /** An array of allowed OAuth2 grant types for the client. */\n allowedGrants: string[];\n\n /** An array of scopes that the client is allowed to request. */\n scopes: string[];\n\n /** Whether the client is allowed to use plain text PKCE. */\n allowPlainTextPkce?: boolean;\n}\n\n/**\n * Represents an OAuth2 token (access token and optional refresh token).\n * @see RFC 6749, Section 1.4 Access Token\n * @see RFC 6749, Section 1.5 Refresh Token\n */\nexport interface Token {\n /** The access token string. */\n accessToken: string;\n\n /** The expiration date and time of the access token. */\n accessTokenExpiresAt: Date;\n\n /** Optional: The refresh token string. */\n refreshToken?: string;\n\n /** Optional: The expiration date and time of the refresh token. */\n refreshTokenExpiresAt?: Date;\n\n /** The scope of the token. */\n scope: string;\n\n /** The ID of the client associated with the token. */\n clientId: string;\n\n /** The ID of the user associated with the token. */\n userId: string;\n}\n\n/**\n * Represents an OAuth2 authorization code.\n * @see RFC 6749, Section 1.3.1 Authorization Code\n * @see RFC 7636, Section 4. Protocol (PKCE)\n */\nexport interface AuthorizationCode {\n /** The authorization code string. */\n code: string;\n\n /** The expiration date and time of the authorization code. */\n expiresAt: Date;\n\n /** The redirect URI used in the authorization request. */\n redirectUri: string;\n\n /** The scope requested during authorization. */\n scope: string;\n\n /** The ID of the client associated with the authorization code. */\n clientId: string;\n\n /** The ID of the user associated with the authorization code. */\n userId: string;\n\n /** The PKCE code challenge. */\n codeChallenge: string;\n\n /** The PKCE code challenge method (S256 or plain). */\n codeChallengeMethod: 'S256' | 'plain';\n}\n\n/**\n * Defines the contract for a storage adapter, responsible for persisting and retrieving OAuth2-related data.\n * This interface abstracts the underlying data storage mechanism.\n */\nexport interface StorageAdapter<U extends any = any> {\n /**\n * Retrieves a client by its ID.\n * @param clientId The ID of the client.\n * @returns A Promise that resolves to the Client object or null if not found.\n */\n getClient(clientId: string): Promise<Client | null>;\n\n /**\n * Saves a token (access token and/or refresh token).\n * @param token The Token object to save.\n * @returns A Promise that resolves when the token is saved.\n */\n saveToken(token: Token): Promise<void>;\n\n /**\n * Retrieves an access token.\n * @param accessToken The access token string.\n * @returns A Promise that resolves to the Token object or null if not found.\n */\n getAccessToken(accessToken: string): Promise<Token | null>;\n\n /**\n * Retrieves a refresh token.\n * @param refreshToken The refresh token string.\n * @returns A Promise that resolves to the Token object or null if not found.\n */\n getRefreshToken(refreshToken: string): Promise<Token | null>;\n\n /**\n * Saves an authorization code.\n * @param code The AuthorizationCode object to save.\n * @returns A Promise that resolves when the authorization code is saved.\n */\n saveAuthorizationCode(code: AuthorizationCode): Promise<void>;\n\n /**\n * Retrieves an authorization code.\n * @param code The authorization code string.\n * @returns A Promise that resolves to the AuthorizationCode object or null if not found.\n */\n getAuthorizationCode(code: string): Promise<AuthorizationCode | null>;\n\n /**\n * Deletes an authorization code.\n * @param code The authorization code string to delete.\n * @returns A Promise that resolves when the authorization code is deleted.\n */\n deleteAuthorizationCode(code: string): Promise<void>;\n\n /**\n * Revokes a token (access token or refresh token).\n * @param token The token string to revoke.\n * @returns A Promise that resolves when the token is revoked.\n */\n revokeToken(token: string): Promise<void>;\n\n /**\n * Retrieves a user by their ID.\n * @param userId The ID of the user.\n * @returns A Promise that resolves to the user object or null if not found.\n */\n getUser(userId: string): Promise<any | null>;\n\n /**\n * Retrieves a user by their credentials (username and password), if the credentials are invalid, it returns null.\n * @param username The username of the user.\n * @param password The password of the user.\n */\n getUserByCredentials(username: string, password: string): Promise<any | null>;\n}\n\n/**\n * Defines the contract for an OAuth2 grant type handler.\n * @see RFC 6749, Section 1.3 Authorization Grant\n */\nexport interface Grant {\n /**\n * The Grant type identifier (e.g., 'authorization_code', 'client_credentials'), this identifer is unique across all grants.\n * This is used to identify the grant type in requests.\n */\n type: string;\n\n /**\n * Optional: An array of response types supported by this grant, e.g., ['code', 'token']. This is used to identify the grant type in requests\n * that can support the response type for the `/authorize` endpoint.\n */\n responseTypes?: string[];\n\n /**\n * Called on the `/authorize` endpoint (e.g., for `authorization_code`).\n */\n handleAuthorization?(context: Context): Promise<OAuth2Response>;\n\n /**\n * Called on the `/token` endpoint (e.g., for exchanging a code).\n */\n handleToken?(context: Context): Promise<OAuth2Response>;\n\n /**\n * Optional validation before token issuance (e.g., PKCE, scopes, audience).\n */\n validate?(context: Context): Promise<void>;\n\n /**\n * Optional hook to resolve scopes (may throw if invalid).\n */\n resolveScopes?(context: Context): Promise<string[]>;\n}\n\n/**\n * Parameters for token generation, providing all necessary context and data.\n */\nexport interface TokenGenerationParams {\n /** The authenticated client */\n client: Client;\n\n /** The user ID associated with the token */\n userId: string;\n\n /** The scope for the token */\n scope: string;\n\n /** Additional metadata that can be included in the token */\n metadata?: Record<string, any>;\n}\n\n/**\n * Interface for defining a TokenStrategy, which is responsible for generating and validating tokens.\n * This interface provides a clean abstraction for different token implementations (JWT, opaque, etc.)\n */\nexport interface TokenStrategy {\n /**\n * Generates a new access token with the specified parameters.\n * @param params Token generation parameters including client, user, and scope information\n * @param context The context containing request details and storage adapter\n * @returns A Promise that resolves to a Token object containing the access token\n */\n generateAccessToken(params: TokenGenerationParams, context: Context): Promise<Token>;\n\n /**\n * Validates an access token and returns token information if valid.\n * @param accessToken The access token string to validate\n * @param context The context containing request details and storage adapter\n * @returns A Promise that resolves to a Token object if valid, or null if invalid\n */\n validateAccessToken(accessToken: string, context: Context): Promise<Token | null>;\n\n /**\n * Generates a new refresh token with the specified parameters.\n * @param params Token generation parameters including client, user, and scope information\n * @param context The context containing request details and storage adapter\n * @returns A Promise that resolves to a Token object containing the refresh token\n */\n generateRefreshToken(params: TokenGenerationParams, context: Context): Promise<Token>;\n\n /**\n * Validates a refresh token and returns token information if valid.\n * @param refreshToken The refresh token string to validate\n * @param context The context containing request details and storage adapter\n * @returns A Promise that resolves to a Token object if valid, or null if invalid\n */\n validateRefreshToken(refreshToken: string, context: Context): Promise<Token | null>;\n\n /**\n * Optional: Generate both access and refresh tokens in a single call for efficiency.\n * If not implemented, will fall back to calling generateAccessToken and generateRefreshToken separately.\n * @param params Token generation parameters\n * @param context The context containing request details and storage adapter\n * @returns A Promise that resolves to a Token object containing both tokens\n */\n generateTokenPair?(params: TokenGenerationParams, context: Context): Promise<Token>;\n}\n\n/**\n * Represents the context for an OAuth2 operation, containing request details, storage adapter, and authenticated client.\n */\nexport interface Context {\n /** Server Config */\n config: ServerConfig;\n\n /** The incoming OAuth2 request. */\n request: OAuth2Request;\n\n /** The storage adapter for data persistence. */\n storage: StorageAdapter;\n\n /** Optional: The authenticated client associated with the request. */\n client?: Client; // The authenticated client, if available\n}\n\n/**\n * Defines the configuration options for the OAuth2 server.\n */\nexport interface ServerConfig {\n /** The storage adapter to be used by the server. */\n storage: StorageAdapter;\n /** The token strategy to be used by the server. If not provided, defaults to opaque token strategy. */\n tokenStrategy?: TokenStrategy;\n /** An array of supported grant type handlers. */\n grants: Grant[];\n /** An array of predefined, valid scopes supported by the server. */\n predefinedScopes: string[];\n /** Optional: The lifetime of the access token in seconds. Defaults to 3600 (1 hour). */\n accessTokenLifetime?: number;\n /** Optional: The lifetime of the refresh token in seconds. Defaults to 604800 (7 days). */\n refreshTokenLifetime?: number;\n /** Optional: The lifetime of the authorization code in seconds. Defaults to 600 (10 minutes). */\n authorizationCodeLifetime?: number;\n // logger?: Logger; // TODO: Define Logger interface later\n}\n\n/**\n * Defines the public interface for the OAuth2 server.\n * @see RFC 6749, Section 1.2 Protocol Flow\n */\nexport interface OAuth2Server {\n /**\n * Handles an authorization request.\n * @param request The incoming OAuth2 authorization request.\n * @returns A Promise that resolves to an OAuth2Response.\n */\n authorize(request: OAuth2Request): Promise<OAuth2Response>;\n /**\n * Handles a token request.\n * @param request The incoming OAuth2 token request.\n * @returns A Promise that resolves to an OAuth2Response containing the token details.\n */\n token(request: OAuth2Request): Promise<OAuth2Response>;\n /**\n * Handles a token revocation request.\n * @param request The incoming OAuth2 revocation request.\n * @returns A Promise that resolves to an OAuth2Response with a 200 status code upon successful revocation.\n */\n revoke(request: OAuth2Request): Promise<OAuth2Response>;\n /**\n * Handles a token introspection request.\n * @param request The incoming OAuth2 introspection request.\n * @returns A Promise that resolves to an OAuth2Response containing the token's introspection data.\n */\n introspect(request: OAuth2Request): Promise<OAuth2Response>;\n}\n"],"names":[],"mappings":"AAAA;AACA;AACA;AACO;AACP;AACA;AACA;AACA;AACA;AACO;AACP;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACO;AACP;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACO;AACP;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACO;AACP;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACO;AACP;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACO;AACP;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACO;AACP;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACO;AACP;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACO;AACP;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACO;AACP;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACO;AACP;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACO;AACP;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;"}