@vunexa/lixa 0.0.1-alpha.20 → 0.0.1-alpha.22
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +562 -79
- package/dist/dao/session-cache.d.ts +2 -2
- package/dist/dao/session-cache.d.ts.map +1 -1
- package/dist/dao/state-cache.d.ts +3 -3
- package/dist/dao/state-cache.d.ts.map +1 -1
- package/dist/dao/types.d.ts +246 -5
- package/dist/dao/types.d.ts.map +1 -1
- package/dist/export-types/index.d.ts +852 -49
- package/dist/index.cjs +282 -46
- package/dist/index.cjs.map +1 -1
- package/dist/index.d.cts +853 -46
- package/dist/index.d.ts +11 -3
- package/dist/index.d.ts.map +1 -1
- package/dist/index.js +282 -46
- package/dist/index.js.map +1 -1
- package/dist/lixa.d.ts +187 -18
- package/dist/lixa.d.ts.map +1 -1
- package/dist/models/session.d.ts +163 -7
- package/dist/models/session.d.ts.map +1 -1
- package/dist/providers/IProvider.d.ts +121 -4
- package/dist/providers/IProvider.d.ts.map +1 -1
- package/dist/providers/index.d.ts +0 -2
- package/dist/providers/index.d.ts.map +1 -1
- package/dist/types.d.ts +131 -15
- package/dist/types.d.ts.map +1 -1
- package/package.json +2 -16
- package/dist/IProvider-2tDwRAnH.d.cts +0 -18
- package/dist/IProvider-2tDwRAnH.d.ts +0 -18
- package/dist/export-types/providers.d.ts +0 -61
- package/dist/providers/github.d.ts +0 -13
- package/dist/providers/github.d.ts.map +0 -1
- package/dist/providers/google.d.ts +0 -13
- package/dist/providers/google.d.ts.map +0 -1
- package/dist/providers-entry.cjs +0 -48
- package/dist/providers-entry.cjs.map +0 -1
- package/dist/providers-entry.d.cts +0 -25
- package/dist/providers-entry.d.ts +0 -22
- package/dist/providers-entry.d.ts.map +0 -1
- package/dist/providers-entry.js +0 -20
- package/dist/providers-entry.js.map +0 -1
package/dist/index.js.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["../src/lixa.ts","../src/dao/state-cache.ts","../src/dao/session-cache.ts","../src/models/session.ts"],"sourcesContent":["import { randomBytes } from \"crypto\";\nimport { type LixaConfig, type ProviderConfig } from \"./types\";\nimport { IProvider } from \"./providers\";\nimport { LocalStateCache } from \"./dao/state-cache\";\nimport { SessionDao, StateDao } from \"./dao/types\";\nimport crypto from \"crypto\";\nimport { LocalSessionCache } from \"./dao/session-cache\";\nimport { type Session, type SessionStrategy, DefaultSessionStrategy } from \"./models/session\";\n\n/**\n * Global registry of registered provider names\n */\ntype RegisteredProviders = string;\n\n/**\n * Type representing the keys of configured providers\n */\ntype ConfiguredProviderKey<T extends LixaConfig<any>> = keyof T['providers'];\n\n/**\n * A flexible, provider-agnostic OAuth 2.0 and OpenID Connect (OIDC) client library.\n *\n * @remarks\n * Lixa simplifies multi-provider authentication flows and supports extensible session management.\n *\n * @example\n * ```typescript\n * import { Lixa } from '@vunexa/lixa';\n * import { GoogleProvider } from '@vunexa/lixa/providers';\n * \n * // Register providers before using them\n * Lixa.registerProvider({ google: new GoogleProvider() });\n * \n * const config = Lixa.createConfig({\n * providers: {\n * google: {\n * clientId: 'your-client-id',\n * clientSecret: 'your-client-secret',\n * redirectUri: 'https://yourapp.com/auth/google/callback',\n * scopes: ['openid', 'email', 'profile']\n * }\n * }\n * });\n * \n * const lixa = new Lixa(config);\n * ```\n *\n * @public\n */\nclass Lixa<TConfig extends LixaConfig<any> = LixaConfig> {\n private static CONFIGURED_PROVIDERS: Map<string, IProvider> = new Map();\n private static LOCAL_STATE_CACHE = new LocalStateCache();\n private static LOCAL_SESSION_CACHE = new LocalSessionCache();\n private static DEFAULT_SESSION_STRATEGY = new DefaultSessionStrategy();\n private config: TConfig;\n private stateDao: StateDao;\n private sesionDao: SessionDao;\n private sessionStrategy: SessionStrategy;\n private debug: boolean;\n\n /**\n * Creates a new Lixa instance with the provided configuration.\n *\n * @param config - The configuration object containing provider settings and optional session strategy\n */\n constructor(config: TConfig) {\n // Validate that all providers in config are registered\n const configuredProviders = Object.keys(config.providers);\n const registeredProviders = Lixa.getRegisteredProviders();\n \n for (const provider of configuredProviders) {\n if (!registeredProviders.includes(provider.toLowerCase())) {\n throw new Error(`Provider '${provider}' is not registered. Please register it first using Lixa.registerProvider()`);\n }\n }\n \n this.config = config;\n this.stateDao = config.stateDao || Lixa.LOCAL_STATE_CACHE;\n this.sesionDao = config.sessionDao || Lixa.LOCAL_SESSION_CACHE;\n this.sessionStrategy = config.sessionStrategy || Lixa.DEFAULT_SESSION_STRATEGY;\n this.debug = config.debug || false;\n }\n\n private log(...args: any[]) {\n if (this.debug) {\n console.log('[Lixa]', ...args);\n }\n }\n\n private logError(...args: any[]) {\n if (this.debug) {\n console.error('[Lixa]', ...args);\n }\n }\n\n /**\n * Checks if a provider is both registered and configured for this instance.\n * This is a type guard that narrows the provider type for use with getAuthUrl.\n *\n * @param provider - The provider name to check (case-insensitive)\n * @returns True if the provider is registered and configured, false otherwise\n *\n * @example\n * ```typescript\n * if (lixa.isProviderConfigured(provider)) {\n * // TypeScript now knows provider is a valid ConfiguredProviderKey\n * const authUrl = lixa.getAuthUrl(provider, state);\n * }\n * ```\n */\n public isProviderConfigured<T extends string>(provider: T): provider is T & ConfiguredProviderKey<TConfig> {\n const providerType = provider.toLowerCase();\n return Lixa.CONFIGURED_PROVIDERS.has(providerType) &&\n this.config.providers.hasOwnProperty(providerType);\n }\n\n /**\n * Registers custom OAuth providers for use with Lixa.\n *\n * @param providerMap - A map of provider names to IProvider implementations\n *\n * @example\n * ```typescript\n * class CustomProvider implements IProvider {\n * authorizationEndpoint = 'https://custom.com/oauth/authorize';\n * tokenEndpoint = 'https://custom.com/oauth/token';\n * userInfoEndpoint = 'https://custom.com/api/user';\n * }\n *\n * Lixa.registerProvider({ custom: new CustomProvider() });\n * ```\n */\n public static registerProvider<T extends Record<string, IProvider>>(providerMap: T): void {\n Object.entries(providerMap).forEach(([key, providerImpl]) => {\n Lixa.CONFIGURED_PROVIDERS.set(key.toLowerCase(), providerImpl);\n });\n }\n\n /**\n * Gets the list of registered provider names.\n * \n * @returns Array of registered provider names\n */\n public static getRegisteredProviders(): string[] {\n return Array.from(Lixa.CONFIGURED_PROVIDERS.keys());\n }\n\n /**\n * Creates a type-safe configuration that only allows registered providers.\n * \n * @param config - Configuration object with providers that must be registered\n * @returns The same configuration object, but with type safety for registered providers\n */\n public static createConfig<T extends Record<string, ProviderConfig>>(\n config: LixaConfig<keyof T & string> & { providers: T }\n ): LixaConfig<keyof T & string> {\n // Validate that all providers in config are registered\n const configuredProviders = Object.keys(config.providers);\n const registeredProviders = Lixa.getRegisteredProviders();\n \n for (const provider of configuredProviders) {\n if (!registeredProviders.includes(provider.toLowerCase())) {\n throw new Error(`Provider '${provider}' is not registered. Please register it first using Lixa.registerProvider()`);\n }\n }\n \n return config;\n }\n\n /**\n * Generates a cryptographically secure random state parameter for OAuth flows.\n *\n * @returns A 32-character hexadecimal string\n *\n * @remarks\n * The state parameter is used to prevent CSRF attacks in OAuth flows.\n */\n public static generateRandomState(): string {\n return randomBytes(16).toString(\"hex\");\n }\n\n /**\n * Generates a cryptographically secure code verifier for PKCE flows.\n *\n * @returns A 64-character hexadecimal string\n *\n * @remarks\n * The code verifier is used in PKCE (Proof Key for Code Exchange) to enhance security.\n */\n private static generateCodeVerifier(): string {\n return randomBytes(32).toString(\"hex\");\n }\n\n private static buildCodeChallenge(codeVerifier: string): string {\n const hash = crypto\n .createHash(\"sha256\")\n .update(codeVerifier)\n .digest(\"base64\");\n\n // Convert to base64url\n return hash.replace(/\\+/g, \"-\").replace(/\\//g, \"_\").replace(/=+$/, \"\");\n }\n\n /**\n * Generates the authorization URL for the specified provider.\n *\n * @param provider - The provider name (must be a configured provider key)\n * @param state - The state parameter for CSRF protection\n * @returns The complete authorization URL to redirect users to\n *\n * @throws Error when the provider is not configured\n *\n * @example\n * ```typescript\n * const state = Lixa.generateRandomState();\n * const authUrl = lixa.getAuthUrl('google', state);\n * res.redirect(authUrl);\n * ```\n */\n public getAuthUrl(provider: ConfiguredProviderKey<TConfig> | string, state: string): string {\n const providerType = String(provider).toLowerCase();\n const providerConfig = this.findProviderByType(providerType);\n const providerImpl = Lixa.CONFIGURED_PROVIDERS.get(providerType);\n\n if (!providerConfig || !providerImpl) {\n throw new Error(`Provider ${providerType} not configured`);\n }\n\n const codeVerifier = Lixa.generateCodeVerifier();\n const codeChallenge = Lixa.buildCodeChallenge(codeVerifier);\n\n // Cache the state paramaeter with TTL of 5 minutes (300 seconds)\n // We dont care about value. we are onl interested in key existence\n this.stateDao.saveState(\n state,\n {\n createdAt: Date.now(),\n provider: providerType,\n codeVerifier,\n },\n 300 // 5 minutes in seconds\n );\n\n const params = new URLSearchParams({\n client_id: providerConfig.clientId,\n redirect_uri: providerConfig.redirectUri,\n scope: providerConfig.scopes.join(\" \"),\n state,\n response_type: \"code\",\n code_challenge: codeChallenge,\n code_challenge_method: \"S256\",\n ...providerConfig.extraConfig,\n });\n\n return `${providerImpl.authorizationEndpoint}?${params.toString()}`;\n }\n\n /**\n * Handles the OAuth callback and creates a user session.\n *\n * @param provider - The provider name (must be a configured provider key)\n * @param code - The authorization code from the provider\n * @param state - The state parameter for validation\n * @returns A Promise that resolves to the session ID\n *\n * @throws Error when code or state is missing/invalid, or provider is not configured\n *\n * @example\n * ```typescript\n * const sessionId = await lixa.handleCallback({\n * provider: 'google',\n * code: req.query.code,\n * state: req.query.state\n * });\n * ```\n */\n public async handleCallback({\n provider,\n code,\n state,\n }: {\n provider: ConfiguredProviderKey<TConfig> | string;\n code: string;\n state?: string;\n }): Promise<string> {\n if (!code || code.trim() === \"\") {\n throw new Error(\"Invalid or missing code in callback\");\n }\n\n if (!state || state.trim() === \"\") {\n throw new Error(\"Invalid or missing state in callback\");\n }\n\n //Validate state here\n const cachedState = await this.stateDao.getState(state);\n if (!cachedState) {\n throw new Error(\"Invalid or expired state\");\n }\n // State is valid, remove it from cache to prevent reuse\n await this.stateDao.deleteState(state);\n\n //Get code verifier from cached state\n const codeVerifier = cachedState.codeVerifier;\n\n const providerType = String(provider).toLowerCase();\n const providerConfig = this.findProviderByType(providerType);\n const providerImpl = Lixa.CONFIGURED_PROVIDERS.get(providerType);\n\n if (!providerConfig || !providerImpl) {\n throw new Error(`Provider ${String(provider)} not configured`);\n }\n\n // Exchange code for tokens and fetch user info here.\n const tokens = await this.exchangeCodeForToken(\n code,\n providerConfig,\n providerImpl,\n codeVerifier\n );\n\n\n const session = await this.sessionStrategy.createSession(tokens);\n\n // Generate unique session ID\n const sessionId = randomBytes(32).toString(\"hex\");\n\n // Store session with 24 hour TTL (86400 seconds)\n await this.sesionDao.saveSession(sessionId, session, 86400);\n\n return sessionId;\n }\n\n public fetchSessionInfo(sessionId: string): Promise<Session | null> {\n return this.sesionDao.getSession(sessionId);\n }\n\n private async exchangeCodeForToken(\n code: string,\n providerConfig: ProviderConfig,\n providerImpl: IProvider,\n codeVerifier: string\n ): Promise<any> {\n // Build the request body\n const body: Record<string, string> = {\n client_id: providerConfig.clientId,\n client_secret: providerConfig.clientSecret,\n code,\n redirect_uri: providerConfig.redirectUri,\n grant_type: \"authorization_code\",\n };\n\n if (codeVerifier) {\n body.code_verifier = codeVerifier;\n }\n const params = new URLSearchParams(body);\n\n this.log('Token Exchange - Request body:', params.toString());\n this.log('Token Exchange - Token endpoint:', providerImpl.tokenEndpoint);\n \n const response = await fetch(providerImpl.tokenEndpoint, {\n method: \"POST\",\n headers: {\n \"Content-Type\": \"application/x-www-form-urlencoded\",\n Accept: \"application/json\",\n },\n body: params.toString(),\n });\n\n if (!response.ok) {\n const errorBody = await response.text();\n this.logError('Token Exchange - Error response:', errorBody);\n throw new Error(\n `Token exchange failed: ${response.status} ${response.statusText} - ${errorBody}`\n );\n }\n\n return response.json();\n }\n\n private findProviderByType(providerType: string): ProviderConfig | undefined {\n return this.config.providers[providerType];\n }\n}\n\nexport { Lixa };\n","import NodeCache from 'node-cache';\nimport { StateDao } from \"./types\";\n\nclass LocalStateCache implements StateDao {\n private cache: NodeCache;\n\n constructor(defaultTtlSeconds: number = 600) {\n this.cache = new NodeCache({ stdTTL: defaultTtlSeconds });\n }\n\n async saveState(state: string, data: any, expiresInSeconds: number): Promise<void> {\n this.cache.set(state, data, expiresInSeconds);\n }\n\n async getState(state: string): Promise<any | null> {\n return this.cache.get(state) || null;\n }\n\n async deleteState(state: string): Promise<void> {\n this.cache.del(state);\n }\n}\n\nexport { LocalStateCache };\n","import NodeCache from 'node-cache';\nimport { SessionDao } from \"./types\";\n\nclass LocalSessionCache implements SessionDao {\n private cache: NodeCache;\n\n constructor(defaultTtlSeconds: number = 600) {\n this.cache = new NodeCache({ stdTTL: defaultTtlSeconds });\n }\n\n async saveSession(state: string, data: any, expiresInSeconds: number): Promise<void> {\n this.cache.set(state, data, expiresInSeconds);\n }\n\n async getSession(state: string): Promise<any | null> {\n return this.cache.get(state) || null;\n }\n\n async deleteSession(state: string): Promise<void> {\n this.cache.del(state);\n }\n}\n\nexport { LocalSessionCache };\n","/**\n * Represents a user session after successful OAuth authentication.\n *\n * @public\n */\nexport interface Session {\n /** The session token (typically the access token) */\n token: string;\n /** Raw token data from the OAuth provider */\n raw: any;\n}\n\n/**\n * Strategy interface for custom session creation.\n *\n * @public\n */\nexport interface SessionStrategy {\n /**\n * Creates a session from OAuth token data.\n *\n * @param userInfo - The token data received from the OAuth provider\n * @returns A Promise that resolves to a Session object\n */\n createSession(userInfo: any): Promise<Session>;\n}\n\n/**\n * Default session strategy that works with any OAuth provider.\n * Extracts common token information and creates a standardized session.\n *\n * @public\n */\nexport class DefaultSessionStrategy implements SessionStrategy {\n /**\n * Creates a session from OAuth token data.\n * Handles common OAuth token formats and extracts the access token.\n *\n * @param tokenData - The token data received from the OAuth provider\n * @returns A Promise that resolves to a Session object\n */\n async createSession(tokenData: any): Promise<Session> {\n // Extract access token from various possible formats\n const accessToken = tokenData.access_token || \n tokenData.accessToken || \n tokenData.token ||\n tokenData;\n\n if (!accessToken || typeof accessToken !== 'string') {\n throw new Error('No valid access token found in OAuth response');\n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AM,OAAO,SAAS;AAAA,IACxB,CAAC;AAED,QAAI,CAAC,SAAS,IAAI;AAChB,YAAM,YAAY,MAAM,SAAS,KAAK;AACtC,WAAK,SAAS,oCAAoC,SAAS;AAC3D,YAAM,IAAI;AAAA,QACR,0BAA0B,SAAS,MAAM,IAAI,SAAS,UAAU,MAAM,SAAS;AAAA,MACjF;AAAA,IACF;AAEA,WAAO,SAAS,KAAK;AAAA,EACvB;AAAA,EAEQ,mBAAmB,cAAkD;AAC3E,WAAO,KAAK,OAAO,UAAU,YAAY;AAAA,EAC3C;AACF;","names":["NodeCache"]}
|
|
1
|
+
{"version":3,"sources":["../src/lixa.ts","../src/dao/state-cache.ts","../src/dao/session-cache.ts","../src/models/session.ts"],"sourcesContent":["import { randomBytes } from \"crypto\";\nimport { type LixaConfig, type ProviderConfig } from \"./types\";\nimport { IProvider } from \"./providers\";\nimport { LocalStateCache } from \"./dao/state-cache\";\nimport { SessionDao, StateDao } from \"./dao/types\";\nimport crypto from \"crypto\";\nimport { LocalSessionCache } from \"./dao/session-cache\";\nimport { type Session, type SessionStrategy, DefaultSessionStrategy, type OAuthTokenResponse } from \"./models/session\";\n\n/**\n * Type representing the keys of configured providers\n */\ntype ConfiguredProviderKey<T extends LixaConfig<Record<string, ProviderConfig>>> = keyof T['providers'];\n\n/**\n * A flexible, provider-agnostic OAuth 2.0 and OpenID Connect (OIDC) client library.\n *\n * @remarks\n * Lixa simplifies multi-provider authentication flows and supports extensible session management.\n * Providers can be passed inline in the configuration, eliminating the need for pre-registration.\n *\n * @example\n * Using built-in providers from \\@vunexa/lixa-providers:\n * ```typescript\n * import { Lixa } from '@vunexa/lixa';\n * import { GoogleProvider } from '@vunexa/lixa-providers';\n * \n * const lixa = new Lixa({\n * providers: {\n * google: {\n * provider: new GoogleProvider(),\n * clientId: 'your-client-id',\n * clientSecret: 'your-client-secret',\n * redirectUri: 'https://yourapp.com/auth/google/callback',\n * scopes: ['openid', 'email', 'profile']\n * }\n * }\n * });\n * ```\n * \n * @example\n * Using custom inline providers:\n * ```typescript\n * import { Lixa, IProvider } from '@vunexa/lixa';\n * \n * const customProvider: IProvider = {\n * authorizationEndpoint: 'https://custom.com/oauth/authorize',\n * tokenEndpoint: 'https://custom.com/oauth/token',\n * userInfoEndpoint: 'https://custom.com/api/user'\n * };\n * \n * const lixa = new Lixa({\n * providers: {\n * custom: {\n * provider: customProvider,\n * clientId: 'your-client-id',\n * clientSecret: 'your-client-secret',\n * redirectUri: 'https://yourapp.com/auth/custom/callback',\n * scopes: ['read:user']\n * }\n * }\n * });\n * ```\n *\n * @public\n */\nclass Lixa<TConfig extends LixaConfig<Record<string, ProviderConfig>> = LixaConfig> {\n private static DEFAULT_PROVIDERS: Map<string, IProvider> = new Map();\n private static CONFIGURED_PROVIDERS: Map<string, IProvider> = new Map(); // Legacy registry for backward compatibility\n private static LOCAL_STATE_CACHE = new LocalStateCache();\n private static LOCAL_SESSION_CACHE = new LocalSessionCache();\n private static DEFAULT_SESSION_STRATEGY = new DefaultSessionStrategy();\n private config: TConfig;\n private stateDao: StateDao;\n private sesionDao: SessionDao;\n private sessionStrategy: SessionStrategy;\n private debug: boolean;\n\n /**\n * Creates a new Lixa instance with the provided configuration.\n * \n * @remarks\n * Providers can be passed inline in the configuration using the `provider` field.\n * Provider resolution priority: inline custom provider \\> default providers \\> legacy registry.\n * \n * @param config - The configuration object containing provider settings and optional session strategy\n * \n * @throws Error when provider configuration is missing required fields\n * @throws Error when provider implementation is missing required properties\n * @throws Error when provider is not available and no inline implementation is provided\n */\n constructor(config: TConfig) {\n this.config = config;\n this.stateDao = config.stateDao || Lixa.LOCAL_STATE_CACHE;\n this.sesionDao = config.sessionDao || Lixa.LOCAL_SESSION_CACHE;\n this.sessionStrategy = config.sessionStrategy || Lixa.DEFAULT_SESSION_STRATEGY;\n this.debug = config.debug || false;\n \n this.log('INFO', 'Init', 'Initializing Lixa instance', { \n providers: Object.keys(config.providers),\n debug: this.debug \n });\n \n // Validate and extract providers from configuration\n for (const [providerName, providerConfig] of Object.entries(config.providers)) {\n const name = providerName.toLowerCase();\n const typedConfig = providerConfig as ProviderConfig;\n \n // Validate provider configuration has required credentials\n this.validateProviderConfig(providerName, typedConfig);\n \n // If provider config includes a custom provider implementation, validate it\n if (typedConfig.provider) {\n this.validateProviderImplementation(providerName, typedConfig.provider);\n this.log('INFO', 'Init', `Registered inline provider: ${providerName}`);\n } else {\n // Check if it's available in default providers or legacy registry\n if (!Lixa.DEFAULT_PROVIDERS.has(name) && !Lixa.CONFIGURED_PROVIDERS.has(name)) {\n this.log('ERROR', 'Init', `Provider '${providerName}' not available`);\n throw new Error(\n `Provider '${providerName}' is not available. ` +\n `Either import it from '@vunexa/lixa-providers' and include it in the configuration, ` +\n `or provide a custom implementation using the 'provider' field: ` +\n `{ provider: new CustomProvider(), clientId: '...', ... }`\n );\n }\n this.log('INFO', 'Init', `Using registered provider: ${providerName}`);\n }\n }\n \n this.log('INFO', 'Init', 'Lixa instance initialized successfully');\n }\n \n /**\n * Validates that a provider configuration has all required credentials.\n * \n * @param name - The provider name\n * @param config - The provider configuration\n * @throws Error when required fields are missing or invalid\n */\n private validateProviderConfig(name: string, config: ProviderConfig): void {\n const requiredFields: (keyof ProviderConfig)[] = ['clientId', 'clientSecret', 'redirectUri', 'scopes'];\n const missingFields = requiredFields.filter(field => {\n const value = config[field];\n return value === undefined || value === null || (typeof value === 'string' && value.trim() === '');\n });\n \n if (missingFields.length > 0) {\n throw new Error(\n `Provider '${name}' configuration is missing required fields: ${missingFields.join(', ')}`\n );\n }\n \n // Validate scopes is an array\n if (!Array.isArray(config.scopes)) {\n throw new Error(\n `Provider '${name}' configuration error: 'scopes' must be an array of strings`\n );\n }\n \n if (config.scopes.length === 0) {\n throw new Error(\n `Provider '${name}' configuration error: 'scopes' array cannot be empty`\n );\n }\n }\n \n /**\n * Validates that a provider implementation has all required properties.\n * \n * @param name - The provider name\n * @param provider - The provider implementation\n * @throws Error when required properties are missing\n */\n private validateProviderImplementation(name: string, provider: IProvider): void {\n const requiredProps: (keyof IProvider)[] = ['authorizationEndpoint', 'tokenEndpoint', 'userInfoEndpoint'];\n const missingProps = requiredProps.filter(prop => {\n const value = provider[prop];\n return !value || typeof value !== 'string' || value.trim() === '';\n });\n \n if (missingProps.length > 0) {\n throw new Error(\n `Provider '${name}' implementation is missing required properties: ${missingProps.join(', ')}. ` +\n `All IProvider implementations must define: authorizationEndpoint, tokenEndpoint, and userInfoEndpoint.`\n );\n }\n }\n\n /**\n * Structured debug logging with standardized format.\n * \n * @param level - Log level (INFO, WARN, ERROR)\n * @param context - Context of the log (Init, Auth, Token, Session, State)\n * @param message - Log message\n * @param data - Optional data to log\n * \n * @remarks\n * Format: [Lixa] [timestamp] [level] [context] message\n * Only logs when debug mode is enabled.\n */\n private log(level: 'INFO' | 'WARN' | 'ERROR', context: 'Init' | 'Auth' | 'Token' | 'Session' | 'State', message: string, data?: Record<string, unknown>): void {\n if (!this.debug) return;\n \n const timestamp = new Date().toISOString();\n const prefix = `[Lixa] [${timestamp}] [${level}] [${context}]`;\n \n if (data !== undefined) {\n console.log(`${prefix} ${message}`, data);\n } else {\n console.log(`${prefix} ${message}`);\n }\n }\n\n /**\n * Checks if a provider is configured for this instance.\n * This is a type guard that narrows the provider type for use with getAuthUrl.\n *\n * @param provider - The provider name to check (case-insensitive)\n * @returns True if the provider is configured, false otherwise\n *\n * @example\n * ```typescript\n * if (lixa.isProviderConfigured(provider)) {\n * // TypeScript now knows provider is a valid ConfiguredProviderKey\n * const authUrl = lixa.getAuthUrl(provider, state);\n * }\n * ```\n */\n public isProviderConfigured<T extends string>(provider: T): provider is T & ConfiguredProviderKey<TConfig> {\n const providerType = provider.toLowerCase();\n return this.config.providers.hasOwnProperty(providerType);\n }\n \n /**\n * Gets a provider implementation by name.\n * Resolution priority: inline custom provider \\> default providers \\> legacy registry\n * \n * @param name - The provider name (case-insensitive)\n * @param config - The provider configuration\n * @returns The provider implementation\n * @throws Error when provider is not found\n */\n private getProvider(name: string, config: ProviderConfig): IProvider {\n // First check if provider is inline in config\n if (config.provider) {\n return config.provider;\n }\n \n // Then check default providers\n const lowerName = name.toLowerCase();\n const defaultProvider = Lixa.DEFAULT_PROVIDERS.get(lowerName);\n if (defaultProvider) {\n return defaultProvider;\n }\n \n // Finally check legacy registry for backward compatibility\n const legacyProvider = Lixa.CONFIGURED_PROVIDERS.get(lowerName);\n if (legacyProvider) {\n return legacyProvider;\n }\n \n throw new Error(\n `Provider '${name}' not found. ` +\n `Ensure the provider is included in the configuration with a 'provider' field, ` +\n `or registered using Lixa.registerProvider().`\n );\n }\n\n /**\n * Registers custom OAuth providers for use with Lixa.\n * \n * @deprecated This method is maintained for backward compatibility.\n * The recommended approach is to pass providers inline in the configuration:\n * ```typescript\n * const lixa = new Lixa({\n * providers: {\n * custom: {\n * provider: new CustomProvider(),\n * clientId: '...',\n * // ...\n * }\n * }\n * });\n * ```\n *\n * @param providerMap - A map of provider names to IProvider implementations\n *\n * @example\n * Legacy usage (still supported):\n * ```typescript\n * class CustomProvider implements IProvider {\n * authorizationEndpoint = 'https://custom.com/oauth/authorize';\n * tokenEndpoint = 'https://custom.com/oauth/token';\n * userInfoEndpoint = 'https://custom.com/api/user';\n * }\n *\n * Lixa.registerProvider({ custom: new CustomProvider() });\n * ```\n */\n public static registerProvider<T extends Record<string, IProvider>>(providerMap: T): void {\n Object.entries(providerMap).forEach(([key, providerImpl]) => {\n Lixa.CONFIGURED_PROVIDERS.set(key.toLowerCase(), providerImpl);\n });\n }\n\n /**\n * Gets the list of registered provider names.\n * \n * @returns Array of registered provider names\n */\n public static getRegisteredProviders(): string[] {\n return Array.from(Lixa.CONFIGURED_PROVIDERS.keys());\n }\n\n /**\n * Creates a type-safe configuration.\n * \n * @deprecated This method is maintained for backward compatibility.\n * You can now pass configuration directly to the Lixa constructor without this helper.\n * \n * @param config - Configuration object with provider settings\n * @returns The same configuration object with type safety\n * \n * @example\n * New approach (recommended):\n * ```typescript\n * const lixa = new Lixa({\n * providers: {\n * google: {\n * provider: new GoogleProvider(),\n * clientId: '...',\n * // ...\n * }\n * }\n * });\n * ```\n */\n public static createConfig<T extends Record<string, ProviderConfig>>(\n config: LixaConfig<T> & { providers: T }\n ): LixaConfig<T> {\n return config;\n }\n\n /**\n * Generates a cryptographically secure random state parameter for OAuth flows.\n *\n * @returns A 32-character hexadecimal string\n *\n * @remarks\n * The state parameter is used to prevent CSRF attacks in OAuth flows.\n */\n public static generateRandomState(): string {\n return randomBytes(16).toString(\"hex\");\n }\n\n /**\n * Generates a cryptographically secure code verifier for PKCE flows.\n *\n * @returns A 64-character hexadecimal string (32 random bytes encoded as hex)\n *\n * @remarks\n * This method implements the code verifier generation as specified in RFC 7636 (PKCE).\n * \n * **PKCE (Proof Key for Code Exchange)** is a security extension to OAuth 2.0 that\n * prevents authorization code interception attacks. It's especially important for\n * public clients (mobile apps, SPAs) but is recommended for all OAuth flows.\n * \n * **Generation methodology:**\n * 1. Generate 32 cryptographically random bytes using Node.js crypto.randomBytes()\n * 2. Encode the bytes as a hexadecimal string (64 characters)\n * 3. The verifier is stored securely and used later in the token exchange\n * \n * **RFC 7636 Requirements:**\n * - Minimum length: 43 characters\n * - Maximum length: 128 characters\n * - Character set: [A-Z] / [a-z] / [0-9] / \"-\" / \".\" / \"_\" / \"~\"\n * - This implementation produces 64 hex characters, meeting the requirements\n * \n * The code verifier is:\n * - Generated when creating the authorization URL\n * - Stored in state cache with the state parameter\n * - Retrieved during callback handling\n * - Sent to the token endpoint to prove the client's identity\n * \n * @see {@link https://datatracker.ietf.org/doc/html/rfc7636 | RFC 7636 - PKCE}\n * @see buildCodeChallenge for the corresponding challenge generation\n * \n * @internal\n */\n private static generateCodeVerifier(): string {\n return randomBytes(32).toString(\"hex\");\n }\n\n /**\n * Generates a code challenge from a code verifier for PKCE flows.\n *\n * @param codeVerifier - The code verifier string (64 hex characters)\n * @returns A base64url-encoded SHA-256 hash of the code verifier\n *\n * @remarks\n * This method implements the code challenge generation as specified in RFC 7636 (PKCE)\n * using the S256 (SHA-256) transformation method.\n * \n * **Challenge generation methodology:**\n * 1. Hash the code verifier using SHA-256\n * 2. Encode the hash as base64\n * 3. Convert to base64url format (RFC 4648):\n * - Replace '+' with '-'\n * - Replace '/' with '_'\n * - Remove trailing '=' padding\n * \n * **PKCE Flow:**\n * 1. Client generates code_verifier (random string)\n * 2. Client creates code_challenge = BASE64URL(SHA256(code_verifier))\n * 3. Client sends code_challenge to authorization endpoint\n * 4. Authorization server stores the code_challenge\n * 5. Client sends code_verifier to token endpoint\n * 6. Authorization server verifies: SHA256(code_verifier) == code_challenge\n * \n * **Security Benefits:**\n * - Prevents authorization code interception attacks\n * - Even if an attacker intercepts the authorization code, they cannot\n * exchange it for tokens without the original code_verifier\n * - The challenge is sent in the authorization request (public)\n * - The verifier is sent in the token request (should be kept secret)\n * \n * **RFC 7636 Transformation Methods:**\n * - plain: code_challenge = code_verifier (not recommended)\n * - S256: code_challenge = BASE64URL(SHA256(code_verifier)) (recommended, used here)\n * \n * @see {@link https://datatracker.ietf.org/doc/html/rfc7636 | RFC 7636 - PKCE}\n * @see {@link https://datatracker.ietf.org/doc/html/rfc4648#section-5 | RFC 4648 - Base64url Encoding}\n * @see generateCodeVerifier for the verifier generation\n * \n * @internal\n */\n private static buildCodeChallenge(codeVerifier: string): string {\n const hash = crypto\n .createHash(\"sha256\")\n .update(codeVerifier)\n .digest(\"base64\");\n\n // Convert to base64url (RFC 4648 Section 5)\n return hash.replace(/\\+/g, \"-\").replace(/\\//g, \"_\").replace(/=+$/, \"\");\n }\n\n /**\n * Generates the authorization URL for the specified provider.\n *\n * @param provider - The provider name (must be a configured provider key)\n * @param state - The state parameter for CSRF protection\n * @returns The complete authorization URL to redirect users to\n *\n * @throws Error when the provider is not configured\n *\n * @example\n * ```typescript\n * const state = Lixa.generateRandomState();\n * const authUrl = lixa.getAuthUrl('google', state);\n * res.redirect(authUrl);\n * ```\n */\n public getAuthUrl(provider: ConfiguredProviderKey<TConfig> | string, state: string): string {\n const providerType = String(provider).toLowerCase();\n \n this.log('INFO', 'Auth', `Generating authorization URL for provider: ${providerType}`);\n \n const providerConfig = this.findProviderByType(providerType);\n\n if (!providerConfig) {\n this.log('ERROR', 'Auth', `Provider '${String(provider)}' is not configured`);\n throw new Error(`Provider '${String(provider)}' is not configured in this Lixa instance`);\n }\n\n const providerImpl = this.getProvider(providerType, providerConfig);\n\n const codeVerifier = Lixa.generateCodeVerifier();\n const codeChallenge = Lixa.buildCodeChallenge(codeVerifier);\n\n this.log('INFO', 'State', `Saving state for provider: ${providerType}`, { state });\n\n // Cache the state paramaeter with TTL of 5 minutes (300 seconds)\n // We dont care about value. we are onl interested in key existence\n this.stateDao.saveState(\n state,\n {\n createdAt: Date.now(),\n provider: providerType,\n codeVerifier,\n },\n 300 // 5 minutes in seconds\n );\n\n const params = new URLSearchParams({\n client_id: providerConfig.clientId,\n redirect_uri: providerConfig.redirectUri,\n scope: providerConfig.scopes.join(\" \"),\n state,\n response_type: \"code\",\n code_challenge: codeChallenge,\n code_challenge_method: \"S256\",\n ...providerConfig.extraConfig,\n });\n\n const authUrl = `${providerImpl.authorizationEndpoint}?${params.toString()}`;\n this.log('INFO', 'Auth', `Authorization URL generated successfully`, { \n provider: providerType,\n endpoint: providerImpl.authorizationEndpoint \n });\n\n return authUrl;\n }\n\n /**\n * Handles the OAuth callback and creates a user session.\n *\n * @param provider - The provider name (must be a configured provider key)\n * @param code - The authorization code from the provider\n * @param state - The state parameter for validation\n * @returns A Promise that resolves to the session ID\n *\n * @throws Error when code or state is missing/invalid, or provider is not configured\n *\n * @example\n * ```typescript\n * const sessionId = await lixa.handleCallback({\n * provider: 'google',\n * code: req.query.code,\n * state: req.query.state\n * });\n * ```\n */\n public async handleCallback({\n provider,\n code,\n state,\n }: {\n provider: ConfiguredProviderKey<TConfig> | string;\n code: string;\n state?: string;\n }): Promise<string> {\n const providerType = String(provider).toLowerCase();\n this.log('INFO', 'Auth', `Handling OAuth callback for provider: ${providerType}`);\n\n if (!code || code.trim() === \"\") {\n this.log('ERROR', 'Auth', 'Invalid or missing authorization code in callback');\n throw new Error(\"Invalid or missing code in callback\");\n }\n\n if (!state || state.trim() === \"\") {\n this.log('ERROR', 'Auth', 'Invalid or missing state in callback');\n throw new Error(\"Invalid or missing state in callback\");\n }\n\n this.log('INFO', 'State', 'Validating state parameter', { state });\n\n //Validate state here\n const cachedState = await this.stateDao.getState(state);\n if (!cachedState) {\n this.log('ERROR', 'State', 'State validation failed: state not found or expired', { state });\n throw new Error(\"Invalid or expired state\");\n }\n \n this.log('INFO', 'State', 'State validated successfully, removing from cache');\n // State is valid, remove it from cache to prevent reuse\n await this.stateDao.deleteState(state);\n\n //Get code verifier from cached state\n const codeVerifier = cachedState.codeVerifier;\n\n const providerConfig = this.findProviderByType(providerType);\n\n if (!providerConfig) {\n this.log('ERROR', 'Auth', `Provider '${String(provider)}' is not configured`);\n throw new Error(`Provider '${String(provider)}' is not configured in this Lixa instance`);\n }\n\n const providerImpl = this.getProvider(providerType, providerConfig);\n\n this.log('INFO', 'Token', `Exchanging authorization code for tokens`, { provider: providerType });\n\n // Exchange code for tokens and fetch user info here.\n const tokens = await this.exchangeCodeForToken(\n code,\n providerConfig,\n providerImpl,\n codeVerifier\n );\n\n this.log('INFO', 'Token', 'Token exchange successful');\n\n this.log('INFO', 'Session', 'Creating user session');\n const session = await this.sessionStrategy.createSession(tokens);\n\n // Generate unique session ID\n const sessionId = randomBytes(32).toString(\"hex\");\n\n this.log('INFO', 'Session', 'Storing session', { sessionId });\n // Store session with 24 hour TTL (86400 seconds)\n await this.sesionDao.saveSession(sessionId, session, 86400);\n\n this.log('INFO', 'Session', 'Session created successfully', { sessionId });\n\n return sessionId;\n }\n\n public async fetchSessionInfo(sessionId: string): Promise<Session | null> {\n const sessionData = await this.sesionDao.getSession(sessionId);\n return sessionData as Session | null;\n }\n\n private async exchangeCodeForToken(\n code: string,\n providerConfig: ProviderConfig,\n providerImpl: IProvider,\n codeVerifier: string\n ): Promise<OAuthTokenResponse> {\n // Build the request body\n const body: Record<string, string> = {\n client_id: providerConfig.clientId,\n client_secret: providerConfig.clientSecret,\n code,\n redirect_uri: providerConfig.redirectUri,\n grant_type: \"authorization_code\",\n };\n\n if (codeVerifier) {\n body.code_verifier = codeVerifier;\n }\n const params = new URLSearchParams(body);\n\n this.log('INFO', 'Token', 'Sending token exchange request', { \n endpoint: providerImpl.tokenEndpoint \n });\n \n const response = await fetch(providerImpl.tokenEndpoint, {\n method: \"POST\",\n headers: {\n \"Content-Type\": \"application/x-www-form-urlencoded\",\n Accept: \"application/json\",\n },\n body: params.toString(),\n });\n\n if (!response.ok) {\n const errorBody = await response.text();\n this.log('ERROR', 'Token', 'Token exchange failed', { \n status: response.status, \n statusText: response.statusText,\n error: errorBody \n });\n throw new Error(\n `Token exchange failed: ${response.status} ${response.statusText} - ${errorBody}`\n );\n }\n\n this.log('INFO', 'Token', 'Token exchange response received successfully');\n return response.json();\n }\n\n private findProviderByType(providerType: string): ProviderConfig | undefined {\n // Use Object.entries to safely iterate and find the provider\n for (const [key, value] of Object.entries(this.config.providers)) {\n if (key.toLowerCase() === providerType.toLowerCase()) {\n return value as ProviderConfig;\n }\n }\n return undefined;\n }\n}\n\nexport { Lixa };\n","import NodeCache from 'node-cache';\nimport { StateDao, StateData } from \"./types\";\n\nclass LocalStateCache implements StateDao {\n private cache: NodeCache;\n\n constructor(defaultTtlSeconds: number = 600) {\n this.cache = new NodeCache({ stdTTL: defaultTtlSeconds });\n }\n\n async saveState(state: string, data: StateData, expiresInSeconds: number): Promise<void> {\n this.cache.set(state, data, expiresInSeconds);\n }\n\n async getState(state: string): Promise<StateData | null> {\n return this.cache.get<StateData>(state) || null;\n }\n\n async deleteState(state: string): Promise<void> {\n this.cache.del(state);\n }\n}\n\nexport { LocalStateCache };\n","import NodeCache from 'node-cache';\nimport { SessionDao } from \"./types\";\n\nclass LocalSessionCache implements SessionDao {\n private cache: NodeCache;\n\n constructor(defaultTtlSeconds: number = 600) {\n this.cache = new NodeCache({ stdTTL: defaultTtlSeconds });\n }\n\n async saveSession<T = unknown>(state: string, data: T, expiresInSeconds: number): Promise<void> {\n this.cache.set(state, data, expiresInSeconds);\n }\n\n async getSession<T = unknown>(state: string): Promise<T | null> {\n return this.cache.get<T>(state) || null;\n }\n\n async deleteSession(state: string): Promise<void> {\n this.cache.del(state);\n }\n}\n\nexport { LocalSessionCache };\n","/**\n * OAuth 2.0 token response structure.\n * Based on RFC 6749 Section 5.1 and OpenID Connect Core 1.0 Section 3.1.3.3\n * \n * @remarks\n * This interface represents the standard OAuth 2.0 token response with\n * optional OpenID Connect extensions. All OAuth providers should return\n * at minimum the required fields (access_token, token_type).\n * \n * @public\n */\nexport interface OAuthTokenResponse {\n /** \n * OAuth 2.0 access token (required).\n * Used to access protected resources on behalf of the user.\n */\n access_token: string;\n \n /** \n * Token type (required).\n * Typically \"Bearer\" for OAuth 2.0.\n */\n token_type: string;\n \n /** \n * Token expiration time in seconds (optional).\n * Time until the access token expires.\n */\n expires_in?: number;\n \n /** \n * OAuth 2.0 refresh token (optional).\n * Used to obtain new access tokens without re-authentication.\n */\n refresh_token?: string;\n \n /** \n * Granted OAuth scopes (optional).\n * Space-separated list of scopes that were granted.\n */\n scope?: string;\n \n /** \n * OpenID Connect ID token (optional).\n * JWT containing user identity claims (only present for OIDC providers).\n */\n id_token?: string;\n \n /**\n * Additional provider-specific fields.\n * Some providers may include extra fields like user_id, account_id, etc.\n */\n [key: string]: unknown;\n}\n\n/**\n * Represents a user session after successful OAuth authentication.\n * \n * @remarks\n * The Session object is returned by SessionStrategy.createSession() and contains\n * the session identifier and any additional data needed for your application.\n * \n * The structure is intentionally flexible to support various session management\n * approaches (JWT tokens, session IDs, etc.).\n *\n * @public\n */\nexport interface Session<TRaw = OAuthTokenResponse> {\n /** \n * The session token or identifier.\n * This could be an access token, a session ID, a JWT, or any other identifier\n * that your application uses to track authenticated users.\n */\n token: string;\n \n /** \n * Raw session data.\n * Contains the complete OAuth token response and any additional data\n * your SessionStrategy adds (user info, database IDs, etc.).\n * \n * Typical OAuth token data includes:\n * - access_token: OAuth access token\n * - refresh_token: OAuth refresh token (if requested)\n * - expires_in: Token expiration time in seconds\n * - token_type: Token type (usually \"Bearer\")\n * - id_token: OpenID Connect ID token (if using OIDC)\n * - scope: Granted scopes\n */\n raw: TRaw;\n}\n\n/**\n * Strategy interface for custom session creation.\n * \n * @remarks\n * Implement this interface to customize how OAuth tokens are converted into\n * application sessions. This is where you typically:\n * - Decode ID tokens (for OpenID Connect)\n * - Look up or create users in your database\n * - Generate session identifiers\n * - Store session data\n * - Add custom claims or metadata\n * \n * The default implementation (DefaultSessionStrategy) simply extracts the\n * access token and returns it as the session token.\n * \n * @example\n * Custom session strategy with database integration:\n * ```typescript\n * interface CustomSessionData extends OAuthTokenResponse {\n * userId: string;\n * email: string;\n * }\n * \n * class DatabaseSessionStrategy implements SessionStrategy {\n * constructor(private db: Database) {}\n * \n * async createSession(tokenData: OAuthTokenResponse): Promise<Session<CustomSessionData>> {\n * // Decode ID token for OIDC providers\n * const idToken = tokenData.id_token;\n * const payload = decodeJwt(idToken);\n * \n * // Create or update user in database\n * const user = await this.db.users.upsert({\n * email: payload.email,\n * name: payload.name,\n * picture: payload.picture\n * });\n * \n * // Generate session ID\n * const sessionId = generateSecureId();\n * \n * // Store session with tokens\n * await this.db.sessions.create({\n * id: sessionId,\n * userId: user.id,\n * accessToken: tokenData.access_token,\n * refreshToken: tokenData.refresh_token,\n * expiresAt: new Date(Date.now() + (tokenData.expires_in || 3600) * 1000)\n * });\n * \n * return {\n * token: sessionId,\n * raw: {\n * userId: user.id,\n * email: user.email,\n * ...tokenData\n * }\n * };\n * }\n * }\n * ```\n *\n * @public\n */\nexport interface SessionStrategy {\n /**\n * Creates a session from OAuth token data.\n * \n * @param tokenData - The token data received from the OAuth provider's token endpoint\n * @returns A Promise that resolves to a Session object\n * \n * @remarks\n * This method is called after successfully exchanging the authorization code\n * for tokens. The tokenData parameter contains the raw response from the\n * provider's token endpoint.\n * \n * Common token data fields:\n * - access_token: OAuth access token\n * - refresh_token: OAuth refresh token (optional)\n * - expires_in: Token expiration time in seconds\n * - token_type: Token type (usually \"Bearer\")\n * - id_token: OpenID Connect ID token (for OIDC providers)\n * - scope: Granted scopes\n * \n * @throws \\{Error\\} If session creation fails (e.g., database error, invalid token)\n * \n * @example\n * Simple implementation:\n * ```typescript\n * async createSession(tokenData: OAuthTokenResponse): Promise<Session> {\n * return {\n * token: tokenData.access_token,\n * raw: tokenData\n * };\n * }\n * ```\n */\n createSession(tokenData: OAuthTokenResponse): Promise<Session>;\n}\n\n/**\n * Default session strategy that works with any OAuth provider.\n * Extracts common token information and creates a standardized session.\n *\n * @public\n */\nexport class DefaultSessionStrategy implements SessionStrategy {\n /**\n * Creates a session from OAuth token data.\n * Handles common OAuth token formats and extracts the access token.\n *\n * @param tokenData - The token data received from the OAuth provider\n * @returns A Promise that resolves to a Session object\n */\n async createSession(tokenData: OAuthTokenResponse): Promise<Session> {\n if (!tokenData.access_token || typeof tokenData.access_token !== 'string') {\n throw new Error('No valid access token found in OAuth response');\n }\n\n return {\n token: tokenData.access_token,\n raw: tokenData,\n };\n }\n}"],"mappings":";AAAA,SAAS,mBAAmB;;;ACA5B,OAAO,eAAe;AAGtB,IAAM,kBAAN,MAA0C;AAAA,EAChC;AAAA,EAER,YAAY,oBAA4B,KAAK;AAC3C,SAAK,QAAQ,IAAI,UAAU,EAAE,QAAQ,kBAAkB,CAAC;AAAA,EAC1D;AAAA,EAEA,MAAM,UAAU,OAAe,MAAiB,kBAAyC;AACvF,SAAK,MAAM,IAAI,OAAO,MAAM,gBAAgB;AAAA,EAC9C;AAAA,EAEA,MAAM,SAAS,OAA0C;AACvD,WAAO,KAAK,MAAM,IAAe,KAAK,KAAK;AAAA,EAC7C;AAAA,EAEA,MAAM,YAAY,OAA8B;AAC9C,SAAK,MAAM,IAAI,KAAK;AAAA,EACtB;AACF;;;ADhBA,OAAO,YAAY;;;A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
4
4
|
/**
|
|
5
5
|
* Type representing the keys of configured providers
|
|
6
6
|
*/
|
|
7
|
-
type ConfiguredProviderKey<T extends LixaConfig<
|
|
7
|
+
type ConfiguredProviderKey<T extends LixaConfig<Record<string, ProviderConfig>>> = keyof T['providers'];
|
|
8
8
|
/**
|
|
9
9
|
* A flexible, provider-agnostic OAuth 2.0 and OpenID Connect (OIDC) client library.
|
|
10
10
|
*
|
|
11
11
|
* @remarks
|
|
12
12
|
* Lixa simplifies multi-provider authentication flows and supports extensible session management.
|
|
13
|
+
* Providers can be passed inline in the configuration, eliminating the need for pre-registration.
|
|
13
14
|
*
|
|
14
15
|
* @example
|
|
16
|
+
* Using built-in providers from \@vunexa/lixa-providers:
|
|
15
17
|
* ```typescript
|
|
16
18
|
* import { Lixa } from '@vunexa/lixa';
|
|
17
|
-
* import { GoogleProvider } from '@vunexa/lixa
|
|
19
|
+
* import { GoogleProvider } from '@vunexa/lixa-providers';
|
|
18
20
|
*
|
|
19
|
-
*
|
|
20
|
-
* Lixa.registerProvider({ google: new GoogleProvider() });
|
|
21
|
-
*
|
|
22
|
-
* const config = Lixa.createConfig({
|
|
21
|
+
* const lixa = new Lixa({
|
|
23
22
|
* providers: {
|
|
24
23
|
* google: {
|
|
24
|
+
* provider: new GoogleProvider(),
|
|
25
25
|
* clientId: 'your-client-id',
|
|
26
26
|
* clientSecret: 'your-client-secret',
|
|
27
27
|
* redirectUri: 'https://yourapp.com/auth/google/callback',
|
|
@@ -29,13 +29,36 @@ type ConfiguredProviderKey<T extends LixaConfig<any>> = keyof T['providers'];
|
|
|
29
29
|
* }
|
|
30
30
|
* }
|
|
31
31
|
* });
|
|
32
|
+
* ```
|
|
32
33
|
*
|
|
33
|
-
*
|
|
34
|
+
* @example
|
|
35
|
+
* Using custom inline providers:
|
|
36
|
+
* ```typescript
|
|
37
|
+
* import { Lixa, IProvider } from '@vunexa/lixa';
|
|
38
|
+
*
|
|
39
|
+
* const customProvider: IProvider = {
|
|
40
|
+
* authorizationEndpoint: 'https://custom.com/oauth/authorize',
|
|
41
|
+
* tokenEndpoint: 'https://custom.com/oauth/token',
|
|
42
|
+
* userInfoEndpoint: 'https://custom.com/api/user'
|
|
43
|
+
* };
|
|
44
|
+
*
|
|
45
|
+
* const lixa = new Lixa({
|
|
46
|
+
* providers: {
|
|
47
|
+
* custom: {
|
|
48
|
+
* provider: customProvider,
|
|
49
|
+
* clientId: 'your-client-id',
|
|
50
|
+
* clientSecret: 'your-client-secret',
|
|
51
|
+
* redirectUri: 'https://yourapp.com/auth/custom/callback',
|
|
52
|
+
* scopes: ['read:user']
|
|
53
|
+
* }
|
|
54
|
+
* }
|
|
55
|
+
* });
|
|
34
56
|
* ```
|
|
35
57
|
*
|
|
36
58
|
* @public
|
|
37
59
|
*/
|
|
38
|
-
declare class Lixa<TConfig extends LixaConfig<
|
|
60
|
+
declare class Lixa<TConfig extends LixaConfig<Record<string, ProviderConfig>> = LixaConfig> {
|
|
61
|
+
private static DEFAULT_PROVIDERS;
|
|
39
62
|
private static CONFIGURED_PROVIDERS;
|
|
40
63
|
private static LOCAL_STATE_CACHE;
|
|
41
64
|
private static LOCAL_SESSION_CACHE;
|
|
@@ -48,17 +71,52 @@ declare class Lixa<TConfig extends LixaConfig<any> = LixaConfig> {
|
|
|
48
71
|
/**
|
|
49
72
|
* Creates a new Lixa instance with the provided configuration.
|
|
50
73
|
*
|
|
74
|
+
* @remarks
|
|
75
|
+
* Providers can be passed inline in the configuration using the `provider` field.
|
|
76
|
+
* Provider resolution priority: inline custom provider \> default providers \> legacy registry.
|
|
77
|
+
*
|
|
51
78
|
* @param config - The configuration object containing provider settings and optional session strategy
|
|
79
|
+
*
|
|
80
|
+
* @throws Error when provider configuration is missing required fields
|
|
81
|
+
* @throws Error when provider implementation is missing required properties
|
|
82
|
+
* @throws Error when provider is not available and no inline implementation is provided
|
|
52
83
|
*/
|
|
53
84
|
constructor(config: TConfig);
|
|
85
|
+
/**
|
|
86
|
+
* Validates that a provider configuration has all required credentials.
|
|
87
|
+
*
|
|
88
|
+
* @param name - The provider name
|
|
89
|
+
* @param config - The provider configuration
|
|
90
|
+
* @throws Error when required fields are missing or invalid
|
|
91
|
+
*/
|
|
92
|
+
private validateProviderConfig;
|
|
93
|
+
/**
|
|
94
|
+
* Validates that a provider implementation has all required properties.
|
|
95
|
+
*
|
|
96
|
+
* @param name - The provider name
|
|
97
|
+
* @param provider - The provider implementation
|
|
98
|
+
* @throws Error when required properties are missing
|
|
99
|
+
*/
|
|
100
|
+
private validateProviderImplementation;
|
|
101
|
+
/**
|
|
102
|
+
* Structured debug logging with standardized format.
|
|
103
|
+
*
|
|
104
|
+
* @param level - Log level (INFO, WARN, ERROR)
|
|
105
|
+
* @param context - Context of the log (Init, Auth, Token, Session, State)
|
|
106
|
+
* @param message - Log message
|
|
107
|
+
* @param data - Optional data to log
|
|
108
|
+
*
|
|
109
|
+
* @remarks
|
|
110
|
+
* Format: [Lixa] [timestamp] [level] [context] message
|
|
111
|
+
* Only logs when debug mode is enabled.
|
|
112
|
+
*/
|
|
54
113
|
private log;
|
|
55
|
-
private logError;
|
|
56
114
|
/**
|
|
57
|
-
* Checks if a provider is
|
|
115
|
+
* Checks if a provider is configured for this instance.
|
|
58
116
|
* This is a type guard that narrows the provider type for use with getAuthUrl.
|
|
59
117
|
*
|
|
60
118
|
* @param provider - The provider name to check (case-insensitive)
|
|
61
|
-
* @returns True if the provider is
|
|
119
|
+
* @returns True if the provider is configured, false otherwise
|
|
62
120
|
*
|
|
63
121
|
* @example
|
|
64
122
|
* ```typescript
|
|
@@ -69,12 +127,37 @@ declare class Lixa<TConfig extends LixaConfig<any> = LixaConfig> {
|
|
|
69
127
|
* ```
|
|
70
128
|
*/
|
|
71
129
|
isProviderConfigured<T extends string>(provider: T): provider is T & ConfiguredProviderKey<TConfig>;
|
|
130
|
+
/**
|
|
131
|
+
* Gets a provider implementation by name.
|
|
132
|
+
* Resolution priority: inline custom provider \> default providers \> legacy registry
|
|
133
|
+
*
|
|
134
|
+
* @param name - The provider name (case-insensitive)
|
|
135
|
+
* @param config - The provider configuration
|
|
136
|
+
* @returns The provider implementation
|
|
137
|
+
* @throws Error when provider is not found
|
|
138
|
+
*/
|
|
139
|
+
private getProvider;
|
|
72
140
|
/**
|
|
73
141
|
* Registers custom OAuth providers for use with Lixa.
|
|
74
142
|
*
|
|
143
|
+
* @deprecated This method is maintained for backward compatibility.
|
|
144
|
+
* The recommended approach is to pass providers inline in the configuration:
|
|
145
|
+
* ```typescript
|
|
146
|
+
* const lixa = new Lixa({
|
|
147
|
+
* providers: {
|
|
148
|
+
* custom: {
|
|
149
|
+
* provider: new CustomProvider(),
|
|
150
|
+
* clientId: '...',
|
|
151
|
+
* // ...
|
|
152
|
+
* }
|
|
153
|
+
* }
|
|
154
|
+
* });
|
|
155
|
+
* ```
|
|
156
|
+
*
|
|
75
157
|
* @param providerMap - A map of provider names to IProvider implementations
|
|
76
158
|
*
|
|
77
159
|
* @example
|
|
160
|
+
* Legacy usage (still supported):
|
|
78
161
|
* ```typescript
|
|
79
162
|
* class CustomProvider implements IProvider {
|
|
80
163
|
* authorizationEndpoint = 'https://custom.com/oauth/authorize';
|
|
@@ -93,14 +176,31 @@ declare class Lixa<TConfig extends LixaConfig<any> = LixaConfig> {
|
|
|
93
176
|
*/
|
|
94
177
|
static getRegisteredProviders(): string[];
|
|
95
178
|
/**
|
|
96
|
-
* Creates a type-safe configuration
|
|
179
|
+
* Creates a type-safe configuration.
|
|
180
|
+
*
|
|
181
|
+
* @deprecated This method is maintained for backward compatibility.
|
|
182
|
+
* You can now pass configuration directly to the Lixa constructor without this helper.
|
|
183
|
+
*
|
|
184
|
+
* @param config - Configuration object with provider settings
|
|
185
|
+
* @returns The same configuration object with type safety
|
|
97
186
|
*
|
|
98
|
-
* @
|
|
99
|
-
*
|
|
187
|
+
* @example
|
|
188
|
+
* New approach (recommended):
|
|
189
|
+
* ```typescript
|
|
190
|
+
* const lixa = new Lixa({
|
|
191
|
+
* providers: {
|
|
192
|
+
* google: {
|
|
193
|
+
* provider: new GoogleProvider(),
|
|
194
|
+
* clientId: '...',
|
|
195
|
+
* // ...
|
|
196
|
+
* }
|
|
197
|
+
* }
|
|
198
|
+
* });
|
|
199
|
+
* ```
|
|
100
200
|
*/
|
|
101
|
-
static createConfig<T extends Record<string, ProviderConfig>>(config: LixaConfig<
|
|
201
|
+
static createConfig<T extends Record<string, ProviderConfig>>(config: LixaConfig<T> & {
|
|
102
202
|
providers: T;
|
|
103
|
-
}): LixaConfig<
|
|
203
|
+
}): LixaConfig<T>;
|
|
104
204
|
/**
|
|
105
205
|
* Generates a cryptographically secure random state parameter for OAuth flows.
|
|
106
206
|
*
|
|
@@ -113,12 +213,81 @@ declare class Lixa<TConfig extends LixaConfig<any> = LixaConfig> {
|
|
|
113
213
|
/**
|
|
114
214
|
* Generates a cryptographically secure code verifier for PKCE flows.
|
|
115
215
|
*
|
|
116
|
-
* @returns A 64-character hexadecimal string
|
|
216
|
+
* @returns A 64-character hexadecimal string (32 random bytes encoded as hex)
|
|
117
217
|
*
|
|
118
218
|
* @remarks
|
|
119
|
-
*
|
|
219
|
+
* This method implements the code verifier generation as specified in RFC 7636 (PKCE).
|
|
220
|
+
*
|
|
221
|
+
* **PKCE (Proof Key for Code Exchange)** is a security extension to OAuth 2.0 that
|
|
222
|
+
* prevents authorization code interception attacks. It's especially important for
|
|
223
|
+
* public clients (mobile apps, SPAs) but is recommended for all OAuth flows.
|
|
224
|
+
*
|
|
225
|
+
* **Generation methodology:**
|
|
226
|
+
* 1. Generate 32 cryptographically random bytes using Node.js crypto.randomBytes()
|
|
227
|
+
* 2. Encode the bytes as a hexadecimal string (64 characters)
|
|
228
|
+
* 3. The verifier is stored securely and used later in the token exchange
|
|
229
|
+
*
|
|
230
|
+
* **RFC 7636 Requirements:**
|
|
231
|
+
* - Minimum length: 43 characters
|
|
232
|
+
* - Maximum length: 128 characters
|
|
233
|
+
* - Character set: [A-Z] / [a-z] / [0-9] / "-" / "." / "_" / "~"
|
|
234
|
+
* - This implementation produces 64 hex characters, meeting the requirements
|
|
235
|
+
*
|
|
236
|
+
* The code verifier is:
|
|
237
|
+
* - Generated when creating the authorization URL
|
|
238
|
+
* - Stored in state cache with the state parameter
|
|
239
|
+
* - Retrieved during callback handling
|
|
240
|
+
* - Sent to the token endpoint to prove the client's identity
|
|
241
|
+
*
|
|
242
|
+
* @see {@link https://datatracker.ietf.org/doc/html/rfc7636 | RFC 7636 - PKCE}
|
|
243
|
+
* @see buildCodeChallenge for the corresponding challenge generation
|
|
244
|
+
*
|
|
245
|
+
* @internal
|
|
120
246
|
*/
|
|
121
247
|
private static generateCodeVerifier;
|
|
248
|
+
/**
|
|
249
|
+
* Generates a code challenge from a code verifier for PKCE flows.
|
|
250
|
+
*
|
|
251
|
+
* @param codeVerifier - The code verifier string (64 hex characters)
|
|
252
|
+
* @returns A base64url-encoded SHA-256 hash of the code verifier
|
|
253
|
+
*
|
|
254
|
+
* @remarks
|
|
255
|
+
* This method implements the code challenge generation as specified in RFC 7636 (PKCE)
|
|
256
|
+
* using the S256 (SHA-256) transformation method.
|
|
257
|
+
*
|
|
258
|
+
* **Challenge generation methodology:**
|
|
259
|
+
* 1. Hash the code verifier using SHA-256
|
|
260
|
+
* 2. Encode the hash as base64
|
|
261
|
+
* 3. Convert to base64url format (RFC 4648):
|
|
262
|
+
* - Replace '+' with '-'
|
|
263
|
+
* - Replace '/' with '_'
|
|
264
|
+
* - Remove trailing '=' padding
|
|
265
|
+
*
|
|
266
|
+
* **PKCE Flow:**
|
|
267
|
+
* 1. Client generates code_verifier (random string)
|
|
268
|
+
* 2. Client creates code_challenge = BASE64URL(SHA256(code_verifier))
|
|
269
|
+
* 3. Client sends code_challenge to authorization endpoint
|
|
270
|
+
* 4. Authorization server stores the code_challenge
|
|
271
|
+
* 5. Client sends code_verifier to token endpoint
|
|
272
|
+
* 6. Authorization server verifies: SHA256(code_verifier) == code_challenge
|
|
273
|
+
*
|
|
274
|
+
* **Security Benefits:**
|
|
275
|
+
* - Prevents authorization code interception attacks
|
|
276
|
+
* - Even if an attacker intercepts the authorization code, they cannot
|
|
277
|
+
* exchange it for tokens without the original code_verifier
|
|
278
|
+
* - The challenge is sent in the authorization request (public)
|
|
279
|
+
* - The verifier is sent in the token request (should be kept secret)
|
|
280
|
+
*
|
|
281
|
+
* **RFC 7636 Transformation Methods:**
|
|
282
|
+
* - plain: code_challenge = code_verifier (not recommended)
|
|
283
|
+
* - S256: code_challenge = BASE64URL(SHA256(code_verifier)) (recommended, used here)
|
|
284
|
+
*
|
|
285
|
+
* @see {@link https://datatracker.ietf.org/doc/html/rfc7636 | RFC 7636 - PKCE}
|
|
286
|
+
* @see {@link https://datatracker.ietf.org/doc/html/rfc4648#section-5 | RFC 4648 - Base64url Encoding}
|
|
287
|
+
* @see generateCodeVerifier for the verifier generation
|
|
288
|
+
*
|
|
289
|
+
* @internal
|
|
290
|
+
*/
|
|
122
291
|
private static buildCodeChallenge;
|
|
123
292
|
/**
|
|
124
293
|
* Generates the authorization URL for the specified provider.
|
package/dist/lixa.d.ts.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"lixa.d.ts","sourceRoot":"","sources":["../src/lixa.ts"],"names":[],"mappings":"AACA,OAAO,EAAE,KAAK,UAAU,EAAE,KAAK,cAAc,EAAE,MAAM,SAAS,CAAC;AAC/D,OAAO,EAAE,SAAS,EAAE,MAAM,aAAa,CAAC;AAKxC,OAAO,EAAE,KAAK,OAAO,
|
|
1
|
+
{"version":3,"file":"lixa.d.ts","sourceRoot":"","sources":["../src/lixa.ts"],"names":[],"mappings":"AACA,OAAO,EAAE,KAAK,UAAU,EAAE,KAAK,cAAc,EAAE,MAAM,SAAS,CAAC;AAC/D,OAAO,EAAE,SAAS,EAAE,MAAM,aAAa,CAAC;AAKxC,OAAO,EAAE,KAAK,OAAO,EAAyE,MAAM,kBAAkB,CAAC;AAEvH;;GAEG;AACH,KAAK,qBAAqB,CAAC,CAAC,SAA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
|
6
|
+
* This interface represents the standard OAuth 2.0 token response with
|
|
7
|
+
* optional OpenID Connect extensions. All OAuth providers should return
|
|
8
|
+
* at minimum the required fields (access_token, token_type).
|
|
9
|
+
*
|
|
10
|
+
* @public
|
|
11
|
+
*/
|
|
12
|
+
export interface OAuthTokenResponse {
|
|
13
|
+
/**
|
|
14
|
+
* OAuth 2.0 access token (required).
|
|
15
|
+
* Used to access protected resources on behalf of the user.
|
|
16
|
+
*/
|
|
17
|
+
access_token: string;
|
|
18
|
+
/**
|
|
19
|
+
* Token type (required).
|
|
20
|
+
* Typically "Bearer" for OAuth 2.0.
|
|
21
|
+
*/
|
|
22
|
+
token_type: string;
|
|
23
|
+
/**
|
|
24
|
+
* Token expiration time in seconds (optional).
|
|
25
|
+
* Time until the access token expires.
|
|
26
|
+
*/
|
|
27
|
+
expires_in?: number;
|
|
28
|
+
/**
|
|
29
|
+
* OAuth 2.0 refresh token (optional).
|
|
30
|
+
* Used to obtain new access tokens without re-authentication.
|
|
31
|
+
*/
|
|
32
|
+
refresh_token?: string;
|
|
33
|
+
/**
|
|
34
|
+
* Granted OAuth scopes (optional).
|
|
35
|
+
* Space-separated list of scopes that were granted.
|
|
36
|
+
*/
|
|
37
|
+
scope?: string;
|
|
38
|
+
/**
|
|
39
|
+
* OpenID Connect ID token (optional).
|
|
40
|
+
* JWT containing user identity claims (only present for OIDC providers).
|
|
41
|
+
*/
|
|
42
|
+
id_token?: string;
|
|
43
|
+
/**
|
|
44
|
+
* Additional provider-specific fields.
|
|
45
|
+
* Some providers may include extra fields like user_id, account_id, etc.
|
|
46
|
+
*/
|
|
47
|
+
[key: string]: unknown;
|
|
48
|
+
}
|
|
1
49
|
/**
|
|
2
50
|
* Represents a user session after successful OAuth authentication.
|
|
3
51
|
*
|
|
52
|
+
* @remarks
|
|
53
|
+
* The Session object is returned by SessionStrategy.createSession() and contains
|
|
54
|
+
* the session identifier and any additional data needed for your application.
|
|
55
|
+
*
|
|
56
|
+
* The structure is intentionally flexible to support various session management
|
|
57
|
+
* approaches (JWT tokens, session IDs, etc.).
|
|
58
|
+
*
|
|
4
59
|
* @public
|
|
5
60
|
*/
|
|
6
|
-
export interface Session {
|
|
7
|
-
/**
|
|
61
|
+
export interface Session<TRaw = OAuthTokenResponse> {
|
|
62
|
+
/**
|
|
63
|
+
* The session token or identifier.
|
|
64
|
+
* This could be an access token, a session ID, a JWT, or any other identifier
|
|
65
|
+
* that your application uses to track authenticated users.
|
|
66
|
+
*/
|
|
8
67
|
token: string;
|
|
9
|
-
/**
|
|
10
|
-
|
|
68
|
+
/**
|
|
69
|
+
* Raw session data.
|
|
70
|
+
* Contains the complete OAuth token response and any additional data
|
|
71
|
+
* your SessionStrategy adds (user info, database IDs, etc.).
|
|
72
|
+
*
|
|
73
|
+
* Typical OAuth token data includes:
|
|
74
|
+
* - access_token: OAuth access token
|
|
75
|
+
* - refresh_token: OAuth refresh token (if requested)
|
|
76
|
+
* - expires_in: Token expiration time in seconds
|
|
77
|
+
* - token_type: Token type (usually "Bearer")
|
|
78
|
+
* - id_token: OpenID Connect ID token (if using OIDC)
|
|
79
|
+
* - scope: Granted scopes
|
|
80
|
+
*/
|
|
81
|
+
raw: TRaw;
|
|
11
82
|
}
|
|
12
83
|
/**
|
|
13
84
|
* Strategy interface for custom session creation.
|
|
14
85
|
*
|
|
86
|
+
* @remarks
|
|
87
|
+
* Implement this interface to customize how OAuth tokens are converted into
|
|
88
|
+
* application sessions. This is where you typically:
|
|
89
|
+
* - Decode ID tokens (for OpenID Connect)
|
|
90
|
+
* - Look up or create users in your database
|
|
91
|
+
* - Generate session identifiers
|
|
92
|
+
* - Store session data
|
|
93
|
+
* - Add custom claims or metadata
|
|
94
|
+
*
|
|
95
|
+
* The default implementation (DefaultSessionStrategy) simply extracts the
|
|
96
|
+
* access token and returns it as the session token.
|
|
97
|
+
*
|
|
98
|
+
* @example
|
|
99
|
+
* Custom session strategy with database integration:
|
|
100
|
+
* ```typescript
|
|
101
|
+
* interface CustomSessionData extends OAuthTokenResponse {
|
|
102
|
+
* userId: string;
|
|
103
|
+
* email: string;
|
|
104
|
+
* }
|
|
105
|
+
*
|
|
106
|
+
* class DatabaseSessionStrategy implements SessionStrategy {
|
|
107
|
+
* constructor(private db: Database) {}
|
|
108
|
+
*
|
|
109
|
+
* async createSession(tokenData: OAuthTokenResponse): Promise<Session<CustomSessionData>> {
|
|
110
|
+
* // Decode ID token for OIDC providers
|
|
111
|
+
* const idToken = tokenData.id_token;
|
|
112
|
+
* const payload = decodeJwt(idToken);
|
|
113
|
+
*
|
|
114
|
+
* // Create or update user in database
|
|
115
|
+
* const user = await this.db.users.upsert({
|
|
116
|
+
* email: payload.email,
|
|
117
|
+
* name: payload.name,
|
|
118
|
+
* picture: payload.picture
|
|
119
|
+
* });
|
|
120
|
+
*
|
|
121
|
+
* // Generate session ID
|
|
122
|
+
* const sessionId = generateSecureId();
|
|
123
|
+
*
|
|
124
|
+
* // Store session with tokens
|
|
125
|
+
* await this.db.sessions.create({
|
|
126
|
+
* id: sessionId,
|
|
127
|
+
* userId: user.id,
|
|
128
|
+
* accessToken: tokenData.access_token,
|
|
129
|
+
* refreshToken: tokenData.refresh_token,
|
|
130
|
+
* expiresAt: new Date(Date.now() + (tokenData.expires_in || 3600) * 1000)
|
|
131
|
+
* });
|
|
132
|
+
*
|
|
133
|
+
* return {
|
|
134
|
+
* token: sessionId,
|
|
135
|
+
* raw: {
|
|
136
|
+
* userId: user.id,
|
|
137
|
+
* email: user.email,
|
|
138
|
+
* ...tokenData
|
|
139
|
+
* }
|
|
140
|
+
* };
|
|
141
|
+
* }
|
|
142
|
+
* }
|
|
143
|
+
* ```
|
|
144
|
+
*
|
|
15
145
|
* @public
|
|
16
146
|
*/
|
|
17
147
|
export interface SessionStrategy {
|
|
18
148
|
/**
|
|
19
149
|
* Creates a session from OAuth token data.
|
|
20
150
|
*
|
|
21
|
-
* @param
|
|
151
|
+
* @param tokenData - The token data received from the OAuth provider's token endpoint
|
|
22
152
|
* @returns A Promise that resolves to a Session object
|
|
153
|
+
*
|
|
154
|
+
* @remarks
|
|
155
|
+
* This method is called after successfully exchanging the authorization code
|
|
156
|
+
* for tokens. The tokenData parameter contains the raw response from the
|
|
157
|
+
* provider's token endpoint.
|
|
158
|
+
*
|
|
159
|
+
* Common token data fields:
|
|
160
|
+
* - access_token: OAuth access token
|
|
161
|
+
* - refresh_token: OAuth refresh token (optional)
|
|
162
|
+
* - expires_in: Token expiration time in seconds
|
|
163
|
+
* - token_type: Token type (usually "Bearer")
|
|
164
|
+
* - id_token: OpenID Connect ID token (for OIDC providers)
|
|
165
|
+
* - scope: Granted scopes
|
|
166
|
+
*
|
|
167
|
+
* @throws \{Error\} If session creation fails (e.g., database error, invalid token)
|
|
168
|
+
*
|
|
169
|
+
* @example
|
|
170
|
+
* Simple implementation:
|
|
171
|
+
* ```typescript
|
|
172
|
+
* async createSession(tokenData: OAuthTokenResponse): Promise<Session> {
|
|
173
|
+
* return {
|
|
174
|
+
* token: tokenData.access_token,
|
|
175
|
+
* raw: tokenData
|
|
176
|
+
* };
|
|
177
|
+
* }
|
|
178
|
+
* ```
|
|
23
179
|
*/
|
|
24
|
-
createSession(
|
|
180
|
+
createSession(tokenData: OAuthTokenResponse): Promise<Session>;
|
|
25
181
|
}
|
|
26
182
|
/**
|
|
27
183
|
* Default session strategy that works with any OAuth provider.
|
|
@@ -37,6 +193,6 @@ export declare class DefaultSessionStrategy implements SessionStrategy {
|
|
|
37
193
|
* @param tokenData - The token data received from the OAuth provider
|
|
38
194
|
* @returns A Promise that resolves to a Session object
|
|
39
195
|
*/
|
|
40
|
-
createSession(tokenData:
|
|
196
|
+
createSession(tokenData: OAuthTokenResponse): Promise<Session>;
|
|
41
197
|
}
|
|
42
198
|
//# sourceMappingURL=session.d.ts.map
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"session.d.ts","sourceRoot":"","sources":["../../src/models/session.ts"],"names":[],"mappings":"AAAA
|
|
1
|
+
{"version":3,"file":"session.d.ts","sourceRoot":"","sources":["../../src/models/session.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;GAUG;AACH,MAAM,WAAW,kBAAkB;IACjC;;;OAGG;IACH,YAAY,EAAE,MAAM,CAAC;IAErB;;;OAGG;IACH,UAAU,EAAE,MAAM,CAAC;IAEnB;;;OAGG;IACH,UAAU,CAAC,EAAE,MAAM,CAAC;IAEpB;;;OAGG;IACH,aAAa,CAAC,EAAE,MAAM,CAAC;IAEvB;;;OAGG;IACH,KAAK,CAAC,EAAE,MAAM,CAAC;IAEf;;;OAGG;IACH,QAAQ,CAAC,EAAE,MAAM,CAAC;IAElB;;;OAGG;IACH,CAAC,GAAG,EAAE,MAAM,GAAG,OAAO,CAAC;CACxB;AAED;;;;;;;;;;;GAWG;AACH,MAAM,WAAW,OAAO,CAAC,IAAI,GAAG,kBAAkB;IAChD;;;;OAIG;IACH,KAAK,EAAE,MAAM,CAAC;IAEd;;;;;;;;;;;;OAYG;IACH,GAAG,EAAE,IAAI,CAAC;CACX;AAED;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;GA+DG;AACH,MAAM,WAAW,eAAe;IAC9B;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;OA+BG;IACH,aAAa,CAAC,SAAS,EAAE,kBAAkB,GAAG,OAAO,CAAC,OAAO,CAAC,CAAC;CAChE;AAED;;;;;GAKG;AACH,qBAAa,sBAAuB,YAAW,eAAe;IAC5D;;;;;;OAMG;IACG,aAAa,CAAC,SAAS,EAAE,kBAAkB,GAAG,OAAO,CAAC,OAAO,CAAC;CAUrE"}
|