UNPKG

@wristband/express-auth

Version:

SDK for integrating your ExpressJS application with Wristband. Handles user authentication, session management, and token management.

135 lines (134 loc) 6.39 kB
import { NextFunction, Request, Response } from 'express'; import { AuthConfig, AuthMiddlewareConfig, CallbackResult, LoginConfig, LogoutConfig, TokenData } from './types'; /** * Core service class that handles Wristband authentication operations. * Manages login flows, token exchanges, session validation, and logout functionality. */ export declare class AuthService { private wristbandService; private configResolver; private jwtValidator?; /** * Creates an instance of AuthService. * * @param {AuthConfig} authConfig - Configuration for Wristband authentication. */ constructor(authConfig: AuthConfig); /** * Force load all auto-configurable fields to cache them. This will trigger the API call * and cache the results. Any validation errors will be thrown here (fail-fast). * * @returns {Promise<void>} A Promise that resolves when configuration is preloaded. * @throws {WristbandError} When autoConfigureEnabled is false or auto-configuration fails. */ preloadConfig(): Promise<void>; /** * Initiates a login request by constructing a redirect URL to Wristband's authorization endpoint. * * @param {Request} req - The Express request object. * @param {Response} res - The Express response object. * @param {LoginConfig} [config={}] - Optional configuration for the login flow. * @returns {Promise<string>} A Promise containing the redirect URL to Wristband's Authorize Endpoint. */ login(req: Request, res: Response, config?: LoginConfig): Promise<string>; /** * Handles the OAuth callback from Wristband, exchanging the authorization code for tokens * and retrieving user information. * * @param {Request} req - The Express request object containing query parameters from Wristband. * @param {Response} res - The Express response object. * @returns {Promise<CallbackResult>} A Promise containing the callback result with token data and userinfo, * or a redirect URL if re-authentication is required. * @throws {TypeError} When required query parameters are invalid or missing. * @throws {WristbandError} When an error occurs during the OAuth flow. */ callback(req: Request, res: Response): Promise<CallbackResult>; /** * Initiates logout by revoking the refresh token and constructing a redirect URL * to Wristband's logout endpoint. * * @param {Request} req - The Express request object. * @param {Response} res - The Express response object. * @param {LogoutConfig} [config={ tenantCustomDomain: '' }] - Optional configuration for logout. * @returns {Promise<string>} A Promise containing the redirect URL to Wristband's Logout Endpoint. * @throws {TypeError} When query parameters are invalid or state exceeds 512 characters. */ logout(req: Request, res: Response, config?: LogoutConfig): Promise<string>; /** * Checks if the access token is expired and refreshes it if necessary. * Implements retry logic for transient failures. * * @param {string} refreshToken - The refresh token to use for obtaining a new access token. * @param {number} expiresAt - Unix timestamp in milliseconds when the current token expires. * @returns {Promise<TokenData | null>} A Promise with new token data if refresh occurred, or null if token is still valid. * @throws {TypeError} When refreshToken is invalid or expiresAt is not a positive integer. * @throws {WristbandError} When token refresh fails due to invalid credentials or unexpected errors. */ refreshTokenIfExpired(refreshToken: string, expiresAt: number): Promise<TokenData | null>; /** * Create middleware that ensures authenticated session using multiple strategies. * Tries strategies in order until one succeeds. Supports both SESSION and JWT auth. * * @param {AuthMiddlewareConfig} config - Configuration for the auth middleware. * @returns {Function} Express middleware function that validates authentication. * * @example * ```typescript * // SESSION only * const requireAuth = authService.createMiddlewareAuth({ * authStrategies: ['SESSION'], * sessionConfig: { * sessionOptions: { * secrets: process.env.SESSION_SECRET!, * cookieName: 'my-session', * maxAge: 24 * 60 * 60 * 1000, // 24 hours * enableCsrfProtection: true, * } * } * }); * app.use('/api/protected', requireAuth); * * // JWT only * const requireJwtAuth = authService.createMiddlewareAuth({ * authStrategies: ['JWT'] * }); * app.use('/api/protected', requireJwtAuth); * * // Try SESSION first, fallback to JWT * const requireAuth = authService.createMiddlewareAuth({ * authStrategies: ['SESSION', 'JWT'], * sessionConfig: { * sessionOptions: { * secrets: process.env.SESSION_SECRET!, * enableCsrfProtection: true, * } * } * }); * app.use('/api/protected', requireAuth); * * // Apply at router level * const protectedRouter = express.Router(); * protectedRouter.use(requireAuth); * protectedRouter.get('/orders', (req, res) => { //... }); * ``` */ createAuthMiddleware(config: AuthMiddlewareConfig): (req: Request, res: Response, next: NextFunction) => Promise<void>; /** * Attempts to authenticate a request using a single configured auth strategy. * * This evaluates the provided strategy in isolation and reports whether it * succeeded or failed with a specific reason. Normal authentication failures * are returned as structured results rather than thrown. * * @param req - The incoming Express request to authenticate. * @param strategy - The auth strategy to apply for this attempt. * @param config - The fully normalized middleware configuration. * @returns A structured result describing authentication outcome, session (if successful), strategy used, and failure reason (if failed). */ private tryAuthStrategy; /** * Lazily initializes and returns the JWT validator instance. * Only creates the validator on first use if JWT strategy is configured. */ private getJwtValidator; }