@vunexa/lixa 0.0.1-alpha.3 → 0.0.1-alpha.33

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.
Files changed (48) hide show
  1. package/README.md +1081 -76
  2. package/dist/dao/session-cache.d.ts +10 -0
  3. package/dist/dao/session-cache.d.ts.map +1 -0
  4. package/dist/dao/state-cache.d.ts +12 -0
  5. package/dist/dao/state-cache.d.ts.map +1 -0
  6. package/dist/dao/types.d.ts +370 -0
  7. package/dist/dao/types.d.ts.map +1 -0
  8. package/dist/export-types/index.d.ts +1220 -0
  9. package/dist/export-types/tsdoc-metadata.json +11 -0
  10. package/dist/index.cjs +723 -0
  11. package/dist/index.cjs.map +1 -0
  12. package/dist/index.d.cts +1189 -0
  13. package/dist/index.d.ts +19 -1
  14. package/dist/index.d.ts.map +1 -1
  15. package/dist/index.js +681 -1
  16. package/dist/index.js.map +1 -1
  17. package/dist/lixa.d.ts +322 -11
  18. package/dist/lixa.d.ts.map +1 -1
  19. package/dist/models/session.d.ts +273 -0
  20. package/dist/models/session.d.ts.map +1 -0
  21. package/dist/providers/IProvider.d.ts +128 -0
  22. package/dist/providers/IProvider.d.ts.map +1 -1
  23. package/dist/providers/index.d.ts +0 -2
  24. package/dist/providers/index.d.ts.map +1 -1
  25. package/dist/types.d.ts +167 -16
  26. package/dist/types.d.ts.map +1 -1
  27. package/dist/utils/user-info.d.ts +82 -0
  28. package/dist/utils/user-info.d.ts.map +1 -0
  29. package/package.json +20 -10
  30. package/dist/lixa.js +0 -107
  31. package/dist/lixa.js.map +0 -1
  32. package/dist/providers/IProvider.js +0 -3
  33. package/dist/providers/IProvider.js.map +0 -1
  34. package/dist/providers/github.d.ts +0 -9
  35. package/dist/providers/github.d.ts.map +0 -1
  36. package/dist/providers/github.js +0 -8
  37. package/dist/providers/github.js.map +0 -1
  38. package/dist/providers/google.d.ts +0 -9
  39. package/dist/providers/google.d.ts.map +0 -1
  40. package/dist/providers/google.js +0 -8
  41. package/dist/providers/google.js.map +0 -1
  42. package/dist/providers/index.js +0 -3
  43. package/dist/providers/index.js.map +0 -1
  44. package/dist/types.js +0 -2
  45. package/dist/types.js.map +0 -1
  46. package/dist/utils/constants.js +0 -4
  47. package/dist/utils/constants.js.map +0 -1
  48. package/index.d.ts +0 -63
package/dist/index.cjs ADDED
@@ -0,0 +1,723 @@
1
+ "use strict";
2
+ var __create = Object.create;
3
+ var __defProp = Object.defineProperty;
4
+ var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
5
+ var __getOwnPropNames = Object.getOwnPropertyNames;
6
+ var __getProtoOf = Object.getPrototypeOf;
7
+ var __hasOwnProp = Object.prototype.hasOwnProperty;
8
+ var __export = (target, all) => {
9
+ for (var name in all)
10
+ __defProp(target, name, { get: all[name], enumerable: true });
11
+ };
12
+ var __copyProps = (to, from, except, desc) => {
13
+ if (from && typeof from === "object" || typeof from === "function") {
14
+ for (let key of __getOwnPropNames(from))
15
+ if (!__hasOwnProp.call(to, key) && key !== except)
16
+ __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });
17
+ }
18
+ return to;
19
+ };
20
+ var __toESM = (mod, isNodeMode, target) => (target = mod != null ? __create(__getProtoOf(mod)) : {}, __copyProps(
21
+ // If the importer is in node compatibility mode or this is not an ESM
22
+ // file that has been converted to a CommonJS file using a Babel-
23
+ // compatible transform (i.e. "__esModule" has not been set), then set
24
+ // "default" to the CommonJS "module.exports" for node compatibility.
25
+ isNodeMode || !mod || !mod.__esModule ? __defProp(target, "default", { value: mod, enumerable: true }) : target,
26
+ mod
27
+ ));
28
+ var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod);
29
+
30
+ // src/index.ts
31
+ var src_exports = {};
32
+ __export(src_exports, {
33
+ Lixa: () => Lixa,
34
+ decodeIdToken: () => decodeIdToken,
35
+ determineProviderFromIssuer: () => determineProviderFromIssuer,
36
+ extractUserInfo: () => extractUserInfo,
37
+ fetchUserInfo: () => fetchUserInfo
38
+ });
39
+ module.exports = __toCommonJS(src_exports);
40
+
41
+ // src/lixa.ts
42
+ var import_crypto2 = require("crypto");
43
+
44
+ // src/dao/state-cache.ts
45
+ var import_node_cache = __toESM(require("node-cache"), 1);
46
+ var import_crypto = require("crypto");
47
+ var LocalStateHandler = class {
48
+ cache;
49
+ stateStorage;
50
+ constructor(defaultTtlSeconds = 600) {
51
+ this.cache = new import_node_cache.default({ stdTTL: defaultTtlSeconds });
52
+ this.stateStorage = {
53
+ saveState: async (state, data, expiresInSeconds) => {
54
+ this.cache.set(state, data, expiresInSeconds);
55
+ },
56
+ getState: async (state) => {
57
+ return this.cache.get(state) || null;
58
+ },
59
+ deleteState: async (state) => {
60
+ this.cache.del(state);
61
+ }
62
+ };
63
+ }
64
+ // Default GenerateState implementation
65
+ async generateState(provider) {
66
+ const state = (0, import_crypto.randomBytes)(16).toString("hex");
67
+ const codeVerifier = (0, import_crypto.randomBytes)(32).toString("hex");
68
+ return {
69
+ state,
70
+ data: {
71
+ provider,
72
+ codeVerifier,
73
+ createdAt: Date.now()
74
+ }
75
+ };
76
+ }
77
+ };
78
+
79
+ // src/lixa.ts
80
+ var import_crypto3 = __toESM(require("crypto"), 1);
81
+
82
+ // src/dao/session-cache.ts
83
+ var import_node_cache2 = __toESM(require("node-cache"), 1);
84
+ var LocalSessionHandler = class {
85
+ cache;
86
+ sessionStorage;
87
+ constructor(defaultTtlSeconds = 600) {
88
+ this.cache = new import_node_cache2.default({ stdTTL: defaultTtlSeconds });
89
+ this.sessionStorage = {
90
+ saveSession: async (sessionId, session, expiresInSeconds) => {
91
+ this.cache.set(sessionId, session, expiresInSeconds);
92
+ },
93
+ getSession: async (sessionId) => {
94
+ return this.cache.get(sessionId) || null;
95
+ },
96
+ deleteSession: async (sessionId) => {
97
+ this.cache.del(sessionId);
98
+ }
99
+ };
100
+ }
101
+ // Default GenerateSession implementation
102
+ async GenerateSession(tokenData, providerMetadata) {
103
+ if (!tokenData.access_token || typeof tokenData.access_token !== "string") {
104
+ throw new Error("No valid access token found in OAuth response");
105
+ }
106
+ const session = {
107
+ token: tokenData.access_token,
108
+ raw: tokenData
109
+ };
110
+ return session;
111
+ }
112
+ };
113
+
114
+ // src/lixa.ts
115
+ var Lixa = class _Lixa {
116
+ static DEFAULT_PROVIDERS = /* @__PURE__ */ new Map();
117
+ static CONFIGURED_PROVIDERS = /* @__PURE__ */ new Map();
118
+ // Legacy registry for backward compatibility
119
+ static LOCAL_STATE_HANDLER = new LocalStateHandler();
120
+ static LOCAL_SESSION_HANDLER = new LocalSessionHandler();
121
+ config;
122
+ stateHandler;
123
+ sessionHandler;
124
+ debug;
125
+ /**
126
+ * Creates a new Lixa instance with the provided configuration.
127
+ *
128
+ * @remarks
129
+ * Providers can be passed inline in the configuration using the `provider` field.
130
+ * Provider resolution priority: inline custom provider \> default providers \> legacy registry.
131
+ *
132
+ * @param config - The configuration object containing provider settings and optional session strategy
133
+ *
134
+ * @throws Error when provider configuration is missing required fields
135
+ * @throws Error when provider implementation is missing required properties
136
+ * @throws Error when provider is not available and no inline implementation is provided
137
+ */
138
+ constructor(config) {
139
+ this.config = config;
140
+ this.stateHandler = config.stateHandler || _Lixa.LOCAL_STATE_HANDLER;
141
+ this.sessionHandler = config.sessionHandler || _Lixa.LOCAL_SESSION_HANDLER;
142
+ this.debug = config.debug || false;
143
+ this.log("INFO", "Init", "Initializing Lixa instance", {
144
+ providers: Object.keys(config.providers),
145
+ debug: this.debug
146
+ });
147
+ for (const [providerName, providerConfig] of Object.entries(config.providers)) {
148
+ const name = providerName.toLowerCase();
149
+ const typedConfig = providerConfig;
150
+ this.validateProviderConfig(providerName, typedConfig);
151
+ if (typedConfig.provider) {
152
+ this.validateProviderImplementation(providerName, typedConfig.provider);
153
+ this.log("INFO", "Init", `Registered inline provider: ${providerName}`);
154
+ } else {
155
+ if (!_Lixa.DEFAULT_PROVIDERS.has(name) && !_Lixa.CONFIGURED_PROVIDERS.has(name)) {
156
+ this.log("ERROR", "Init", `Provider '${providerName}' not available`);
157
+ throw new Error(
158
+ `Provider '${providerName}' is not available. Either import it from '@vunexa/lixa-providers' and include it in the configuration, or provide a custom implementation using the 'provider' field: { provider: new CustomProvider(), clientId: '...', ... }`
159
+ );
160
+ }
161
+ this.log("INFO", "Init", `Using registered provider: ${providerName}`);
162
+ }
163
+ }
164
+ this.log("INFO", "Init", "Lixa instance initialized successfully");
165
+ }
166
+ /**
167
+ * Validates that a provider configuration has all required credentials.
168
+ *
169
+ * @param name - The provider name
170
+ * @param config - The provider configuration
171
+ * @throws Error when required fields are missing or invalid
172
+ */
173
+ validateProviderConfig(name, config) {
174
+ const requiredFields = ["clientId", "clientSecret", "redirectUri", "scopes"];
175
+ const missingFields = requiredFields.filter((field) => {
176
+ const value = config[field];
177
+ return value === void 0 || value === null || typeof value === "string" && value.trim() === "";
178
+ });
179
+ if (missingFields.length > 0) {
180
+ throw new Error(
181
+ `Provider '${name}' configuration is missing required fields: ${missingFields.join(", ")}`
182
+ );
183
+ }
184
+ if (!Array.isArray(config.scopes)) {
185
+ throw new Error(
186
+ `Provider '${name}' configuration error: 'scopes' must be an array of strings`
187
+ );
188
+ }
189
+ if (config.scopes.length === 0) {
190
+ throw new Error(
191
+ `Provider '${name}' configuration error: 'scopes' array cannot be empty`
192
+ );
193
+ }
194
+ }
195
+ /**
196
+ * Validates that a provider implementation has all required properties.
197
+ *
198
+ * @param name - The provider name
199
+ * @param provider - The provider implementation
200
+ * @throws Error when required properties are missing
201
+ */
202
+ validateProviderImplementation(name, provider) {
203
+ const requiredProps = ["authorizationEndpoint", "tokenEndpoint", "userInfoEndpoint"];
204
+ const missingProps = requiredProps.filter((prop) => {
205
+ const value = provider[prop];
206
+ return !value || typeof value !== "string" || value.trim() === "";
207
+ });
208
+ if (missingProps.length > 0) {
209
+ throw new Error(
210
+ `Provider '${name}' implementation is missing required properties: ${missingProps.join(", ")}. All IProvider implementations must define: authorizationEndpoint, tokenEndpoint, and userInfoEndpoint.`
211
+ );
212
+ }
213
+ }
214
+ /**
215
+ * Structured debug logging with standardized format.
216
+ *
217
+ * @param level - Log level (INFO, WARN, ERROR)
218
+ * @param context - Context of the log (Init, Auth, Token, Session, State)
219
+ * @param message - Log message
220
+ * @param data - Optional data to log
221
+ *
222
+ * @remarks
223
+ * Format: [Lixa] [timestamp] [level] [context] message
224
+ * Only logs when debug mode is enabled.
225
+ */
226
+ log(level, context, message, data) {
227
+ if (!this.debug) return;
228
+ const timestamp = (/* @__PURE__ */ new Date()).toISOString();
229
+ const prefix = `[Lixa] [${timestamp}] [${level}] [${context}]`;
230
+ if (data !== void 0) {
231
+ console.log(`${prefix} ${message}`, data);
232
+ } else {
233
+ console.log(`${prefix} ${message}`);
234
+ }
235
+ }
236
+ /**
237
+ * Checks if a provider is configured for this instance.
238
+ * This is a type guard that narrows the provider type for use with getAuthUrl.
239
+ *
240
+ * @param provider - The provider name to check (case-insensitive)
241
+ * @returns True if the provider is configured, false otherwise
242
+ *
243
+ * @example
244
+ * ```typescript
245
+ * if (lixa.isProviderConfigured(provider)) {
246
+ * // TypeScript now knows provider is a valid ConfiguredProviderKey
247
+ * const authUrl = lixa.getAuthUrl(provider, state);
248
+ * }
249
+ * ```
250
+ */
251
+ isProviderConfigured(provider) {
252
+ const providerType = provider.toLowerCase();
253
+ return this.config.providers.hasOwnProperty(providerType);
254
+ }
255
+ /**
256
+ * Gets a provider implementation by name.
257
+ * Resolution priority: inline custom provider \> default providers \> legacy registry
258
+ *
259
+ * @param name - The provider name (case-insensitive)
260
+ * @param config - The provider configuration
261
+ * @returns The provider implementation
262
+ * @throws Error when provider is not found
263
+ */
264
+ getProvider(name, config) {
265
+ if (config.provider) {
266
+ return config.provider;
267
+ }
268
+ const lowerName = name.toLowerCase();
269
+ const defaultProvider = _Lixa.DEFAULT_PROVIDERS.get(lowerName);
270
+ if (defaultProvider) {
271
+ return defaultProvider;
272
+ }
273
+ const legacyProvider = _Lixa.CONFIGURED_PROVIDERS.get(lowerName);
274
+ if (legacyProvider) {
275
+ return legacyProvider;
276
+ }
277
+ throw new Error(
278
+ `Provider '${name}' not found. Ensure the provider is included in the configuration with a 'provider' field, or registered using Lixa.registerProvider().`
279
+ );
280
+ }
281
+ /**
282
+ * Registers custom OAuth providers for use with Lixa.
283
+ *
284
+ * @deprecated This method is maintained for backward compatibility.
285
+ * The recommended approach is to pass providers inline in the configuration:
286
+ * ```typescript
287
+ * const lixa = new Lixa({
288
+ * providers: {
289
+ * custom: {
290
+ * provider: new CustomProvider(),
291
+ * clientId: '...',
292
+ * // ...
293
+ * }
294
+ * }
295
+ * });
296
+ * ```
297
+ *
298
+ * @param providerMap - A map of provider names to IProvider implementations
299
+ *
300
+ * @example
301
+ * Legacy usage (still supported):
302
+ * ```typescript
303
+ * class CustomProvider implements IProvider {
304
+ * authorizationEndpoint = 'https://custom.com/oauth/authorize';
305
+ * tokenEndpoint = 'https://custom.com/oauth/token';
306
+ * userInfoEndpoint = 'https://custom.com/api/user';
307
+ * }
308
+ *
309
+ * Lixa.registerProvider({ custom: new CustomProvider() });
310
+ * ```
311
+ */
312
+ static registerProvider(providerMap) {
313
+ Object.entries(providerMap).forEach(([key, providerImpl]) => {
314
+ _Lixa.CONFIGURED_PROVIDERS.set(key.toLowerCase(), providerImpl);
315
+ });
316
+ }
317
+ /**
318
+ * Gets the list of registered provider names.
319
+ *
320
+ * @returns Array of registered provider names
321
+ */
322
+ static getRegisteredProviders() {
323
+ return Array.from(_Lixa.CONFIGURED_PROVIDERS.keys());
324
+ }
325
+ /**
326
+ * Creates a type-safe configuration.
327
+ *
328
+ * @deprecated This method is maintained for backward compatibility.
329
+ * You can now pass configuration directly to the Lixa constructor without this helper.
330
+ *
331
+ * @param config - Configuration object with provider settings
332
+ * @returns The same configuration object with type safety
333
+ *
334
+ * @example
335
+ * New approach (recommended):
336
+ * ```typescript
337
+ * const lixa = new Lixa({
338
+ * providers: {
339
+ * google: {
340
+ * provider: new GoogleProvider(),
341
+ * clientId: '...',
342
+ * // ...
343
+ * }
344
+ * }
345
+ * });
346
+ * ```
347
+ */
348
+ static createConfig(config) {
349
+ return config;
350
+ }
351
+ /**
352
+ * Generates a cryptographically secure random state parameter for OAuth flows.
353
+ *
354
+ * @returns A 32-character hexadecimal string
355
+ *
356
+ * @remarks
357
+ * The state parameter is used to prevent CSRF attacks in OAuth flows.
358
+ */
359
+ static generateRandomState() {
360
+ return (0, import_crypto2.randomBytes)(16).toString("hex");
361
+ }
362
+ /**
363
+ * Generates a cryptographically secure code verifier for PKCE flows.
364
+ *
365
+ * @returns A 64-character hexadecimal string (32 random bytes encoded as hex)
366
+ *
367
+ * @remarks
368
+ * This method implements the code verifier generation as specified in RFC 7636 (PKCE).
369
+ *
370
+ * **PKCE (Proof Key for Code Exchange)** is a security extension to OAuth 2.0 that
371
+ * prevents authorization code interception attacks. It's especially important for
372
+ * public clients (mobile apps, SPAs) but is recommended for all OAuth flows.
373
+ *
374
+ * **Generation methodology:**
375
+ * 1. Generate 32 cryptographically random bytes using Node.js crypto.randomBytes()
376
+ * 2. Encode the bytes as a hexadecimal string (64 characters)
377
+ * 3. The verifier is stored securely and used later in the token exchange
378
+ *
379
+ * **RFC 7636 Requirements:**
380
+ * - Minimum length: 43 characters
381
+ * - Maximum length: 128 characters
382
+ * - Character set: [A-Z] / [a-z] / [0-9] / "-" / "." / "_" / "~"
383
+ * - This implementation produces 64 hex characters, meeting the requirements
384
+ *
385
+ * The code verifier is:
386
+ * - Generated when creating the authorization URL
387
+ * - Stored in state cache with the state parameter
388
+ * - Retrieved during callback handling
389
+ * - Sent to the token endpoint to prove the client's identity
390
+ *
391
+ * @see {@link https://datatracker.ietf.org/doc/html/rfc7636 | RFC 7636 - PKCE}
392
+ * @see buildCodeChallenge for the corresponding challenge generation
393
+ *
394
+ * @internal
395
+ */
396
+ static generateCodeVerifier() {
397
+ return (0, import_crypto2.randomBytes)(32).toString("hex");
398
+ }
399
+ /**
400
+ * Generates a code challenge from a code verifier for PKCE flows.
401
+ *
402
+ * @param codeVerifier - The code verifier string (64 hex characters)
403
+ * @returns A base64url-encoded SHA-256 hash of the code verifier
404
+ *
405
+ * @remarks
406
+ * This method implements the code challenge generation as specified in RFC 7636 (PKCE)
407
+ * using the S256 (SHA-256) transformation method.
408
+ *
409
+ * **Challenge generation methodology:**
410
+ * 1. Hash the code verifier using SHA-256
411
+ * 2. Encode the hash as base64
412
+ * 3. Convert to base64url format (RFC 4648):
413
+ * - Replace '+' with '-'
414
+ * - Replace '/' with '_'
415
+ * - Remove trailing '=' padding
416
+ *
417
+ * **PKCE Flow:**
418
+ * 1. Client generates code_verifier (random string)
419
+ * 2. Client creates code_challenge = BASE64URL(SHA256(code_verifier))
420
+ * 3. Client sends code_challenge to authorization endpoint
421
+ * 4. Authorization server stores the code_challenge
422
+ * 5. Client sends code_verifier to token endpoint
423
+ * 6. Authorization server verifies: SHA256(code_verifier) == code_challenge
424
+ *
425
+ * **Security Benefits:**
426
+ * - Prevents authorization code interception attacks
427
+ * - Even if an attacker intercepts the authorization code, they cannot
428
+ * exchange it for tokens without the original code_verifier
429
+ * - The challenge is sent in the authorization request (public)
430
+ * - The verifier is sent in the token request (should be kept secret)
431
+ *
432
+ * **RFC 7636 Transformation Methods:**
433
+ * - plain: code_challenge = code_verifier (not recommended)
434
+ * - S256: code_challenge = BASE64URL(SHA256(code_verifier)) (recommended, used here)
435
+ *
436
+ * @see {@link https://datatracker.ietf.org/doc/html/rfc7636 | RFC 7636 - PKCE}
437
+ * @see {@link https://datatracker.ietf.org/doc/html/rfc4648#section-5 | RFC 4648 - Base64url Encoding}
438
+ * @see generateCodeVerifier for the verifier generation
439
+ *
440
+ * @internal
441
+ */
442
+ static buildCodeChallenge(codeVerifier) {
443
+ const hash = import_crypto3.default.createHash("sha256").update(codeVerifier).digest("base64");
444
+ return hash.replace(/\+/g, "-").replace(/\//g, "_").replace(/=+$/, "");
445
+ }
446
+ /**
447
+ * Generates the authorization URL for the specified provider.
448
+ *
449
+ * @param provider - The provider name (must be a configured provider key)
450
+ * @param state - The state parameter for CSRF protection
451
+ * @returns The complete authorization URL to redirect users to
452
+ *
453
+ * @throws Error when the provider is not configured
454
+ *
455
+ * @example
456
+ * ```typescript
457
+ * const state = Lixa.generateRandomState();
458
+ * const authUrl = lixa.getAuthUrl('google', state);
459
+ * res.redirect(authUrl);
460
+ * ```
461
+ */
462
+ async getAuthUrl(provider, state) {
463
+ const providerType = String(provider).toLowerCase();
464
+ this.log("INFO", "Auth", `Generating authorization URL for provider: ${providerType}`);
465
+ const providerConfig = this.findProviderByType(providerType);
466
+ if (!providerConfig) {
467
+ this.log("ERROR", "Auth", `Provider '${String(provider)}' is not configured`);
468
+ throw new Error(`Provider '${String(provider)}' is not configured in this Lixa instance`);
469
+ }
470
+ const providerImpl = this.getProvider(providerType, providerConfig);
471
+ let stateValue;
472
+ let codeVerifier;
473
+ if (this.stateHandler.generateState) {
474
+ this.log("INFO", "State", "Calling custom GenerateState");
475
+ const generated = await this.stateHandler.generateState(providerType);
476
+ stateValue = state || generated.state;
477
+ codeVerifier = generated.data.codeVerifier;
478
+ const storage = this.stateHandler.stateStorage || _Lixa.LOCAL_STATE_HANDLER.stateStorage;
479
+ await storage.saveState(stateValue, generated.data, 300);
480
+ } else {
481
+ this.log("INFO", "State", "Using default state generation");
482
+ stateValue = state || (0, import_crypto2.randomBytes)(16).toString("hex");
483
+ codeVerifier = (0, import_crypto2.randomBytes)(32).toString("hex");
484
+ const storage = this.stateHandler.stateStorage || _Lixa.LOCAL_STATE_HANDLER.stateStorage;
485
+ await storage.saveState(
486
+ stateValue,
487
+ {
488
+ createdAt: Date.now(),
489
+ provider: providerType,
490
+ codeVerifier
491
+ },
492
+ 300
493
+ // 5 minutes in seconds
494
+ );
495
+ }
496
+ const codeChallenge = _Lixa.buildCodeChallenge(codeVerifier);
497
+ this.log("INFO", "State", `Saved state for provider: ${providerType}`, { state: stateValue });
498
+ const params = new URLSearchParams({
499
+ client_id: providerConfig.clientId,
500
+ redirect_uri: providerConfig.redirectUri,
501
+ scope: providerConfig.scopes.join(" "),
502
+ state: stateValue,
503
+ response_type: "code",
504
+ code_challenge: codeChallenge,
505
+ code_challenge_method: "S256",
506
+ ...providerConfig.extraConfig
507
+ });
508
+ const authUrl = `${providerImpl.authorizationEndpoint}?${params.toString()}`;
509
+ this.log("INFO", "Auth", `Authorization URL generated successfully`, {
510
+ provider: providerType,
511
+ endpoint: providerImpl.authorizationEndpoint
512
+ });
513
+ return authUrl;
514
+ }
515
+ /**
516
+ * Handles the OAuth callback and creates a user session.
517
+ *
518
+ * @param provider - The provider name (must be a configured provider key)
519
+ * @param code - The authorization code from the provider
520
+ * @param state - The state parameter for validation
521
+ * @returns A Promise that resolves to the session ID
522
+ *
523
+ * @throws Error when code or state is missing/invalid, or provider is not configured
524
+ *
525
+ * @example
526
+ * ```typescript
527
+ * const sessionId = await lixa.handleCallback({
528
+ * provider: 'google',
529
+ * code: req.query.code,
530
+ * state: req.query.state
531
+ * });
532
+ * ```
533
+ */
534
+ async handleCallback({
535
+ provider,
536
+ code,
537
+ state
538
+ }) {
539
+ const providerType = String(provider).toLowerCase();
540
+ this.log("INFO", "Auth", `Handling OAuth callback for provider: ${providerType}`);
541
+ if (!code || code.trim() === "") {
542
+ this.log("ERROR", "Auth", "Invalid or missing authorization code in callback");
543
+ throw new Error("Invalid or missing code in callback");
544
+ }
545
+ if (!state || state.trim() === "") {
546
+ this.log("ERROR", "Auth", "Invalid or missing state in callback");
547
+ throw new Error("Invalid or missing state in callback");
548
+ }
549
+ this.log("INFO", "State", "Validating state parameter", { state });
550
+ const stateStorage = this.stateHandler.stateStorage || _Lixa.LOCAL_STATE_HANDLER.stateStorage;
551
+ const cachedState = await stateStorage.getState(state);
552
+ if (!cachedState) {
553
+ this.log("ERROR", "State", "State validation failed: state not found or expired", { state });
554
+ throw new Error("Invalid or expired state");
555
+ }
556
+ this.log("INFO", "State", "State validated successfully, removing from cache");
557
+ await stateStorage.deleteState(state);
558
+ const codeVerifier = cachedState.codeVerifier;
559
+ const providerConfig = this.findProviderByType(providerType);
560
+ if (!providerConfig) {
561
+ this.log("ERROR", "Auth", `Provider '${String(provider)}' is not configured`);
562
+ throw new Error(`Provider '${String(provider)}' is not configured in this Lixa instance`);
563
+ }
564
+ const providerImpl = this.getProvider(providerType, providerConfig);
565
+ this.log("INFO", "Token", `Exchanging authorization code for tokens`, { provider: providerType });
566
+ const tokens = await this.exchangeCodeForToken(
567
+ code,
568
+ providerConfig,
569
+ providerImpl,
570
+ codeVerifier
571
+ );
572
+ this.log("INFO", "Token", "Token exchange successful");
573
+ this.log("INFO", "Session", "Generating user session");
574
+ const providerMetadata = {
575
+ name: providerType,
576
+ endpoints: {
577
+ authorization: providerImpl.authorizationEndpoint,
578
+ token: providerImpl.tokenEndpoint,
579
+ userInfo: providerImpl.userInfoEndpoint
580
+ }
581
+ };
582
+ const generateSession = this.sessionHandler.generateSession || _Lixa.LOCAL_SESSION_HANDLER.GenerateSession.bind(_Lixa.LOCAL_SESSION_HANDLER);
583
+ if (this.sessionHandler.generateSession) {
584
+ this.log("INFO", "Session", "Calling custom GenerateSession");
585
+ } else {
586
+ this.log("INFO", "Session", "Using default session generation");
587
+ }
588
+ const session = await generateSession(tokens, providerMetadata);
589
+ const sessionId = (0, import_crypto2.randomBytes)(32).toString("hex");
590
+ this.log("INFO", "Session", "Storing session", { sessionId });
591
+ const sessionStorage = this.sessionHandler.sessionStorage || _Lixa.LOCAL_SESSION_HANDLER.sessionStorage;
592
+ await sessionStorage.saveSession(sessionId, session, 86400);
593
+ this.log("INFO", "Session", "Session created successfully", { sessionId });
594
+ return sessionId;
595
+ }
596
+ async fetchSessionInfo(sessionId) {
597
+ const sessionStorage = this.sessionHandler.sessionStorage || _Lixa.LOCAL_SESSION_HANDLER.sessionStorage;
598
+ return await sessionStorage.getSession(sessionId);
599
+ }
600
+ async exchangeCodeForToken(code, providerConfig, providerImpl, codeVerifier) {
601
+ const body = {
602
+ client_id: providerConfig.clientId,
603
+ client_secret: providerConfig.clientSecret,
604
+ code,
605
+ redirect_uri: providerConfig.redirectUri,
606
+ grant_type: "authorization_code"
607
+ };
608
+ if (codeVerifier) {
609
+ body.code_verifier = codeVerifier;
610
+ }
611
+ const params = new URLSearchParams(body);
612
+ this.log("INFO", "Token", "Sending token exchange request", {
613
+ endpoint: providerImpl.tokenEndpoint
614
+ });
615
+ const response = await fetch(providerImpl.tokenEndpoint, {
616
+ method: "POST",
617
+ headers: {
618
+ "Content-Type": "application/x-www-form-urlencoded",
619
+ Accept: "application/json"
620
+ },
621
+ body: params.toString()
622
+ });
623
+ if (!response.ok) {
624
+ const errorBody = await response.text();
625
+ this.log("ERROR", "Token", "Token exchange failed", {
626
+ status: response.status,
627
+ statusText: response.statusText,
628
+ error: errorBody
629
+ });
630
+ throw new Error(
631
+ `Token exchange failed: ${response.status} ${response.statusText} - ${errorBody}`
632
+ );
633
+ }
634
+ this.log("INFO", "Token", "Token exchange response received successfully");
635
+ return response.json();
636
+ }
637
+ findProviderByType(providerType) {
638
+ for (const [key, value] of Object.entries(this.config.providers)) {
639
+ if (key.toLowerCase() === providerType.toLowerCase()) {
640
+ return value;
641
+ }
642
+ }
643
+ return void 0;
644
+ }
645
+ };
646
+
647
+ // src/utils/user-info.ts
648
+ function decodeIdToken(idToken) {
649
+ const parts = idToken.split(".");
650
+ if (parts.length !== 3) {
651
+ throw new Error("Invalid ID token format: expected 3 parts separated by dots");
652
+ }
653
+ const base64Payload = parts[1];
654
+ if (!base64Payload) {
655
+ throw new Error("Invalid ID token: missing payload section");
656
+ }
657
+ const payload = Buffer.from(base64Payload, "base64").toString();
658
+ try {
659
+ return JSON.parse(payload);
660
+ } catch (error) {
661
+ throw new Error("Invalid ID token: failed to parse payload JSON");
662
+ }
663
+ }
664
+ function determineProviderFromIssuer(userInfo) {
665
+ if (!userInfo.iss) {
666
+ return null;
667
+ }
668
+ const issuer = userInfo.iss.toLowerCase();
669
+ if (issuer.includes("accounts.google.com")) {
670
+ return "google";
671
+ }
672
+ if (issuer.includes("github")) {
673
+ return "github";
674
+ }
675
+ return null;
676
+ }
677
+ async function fetchUserInfo(accessToken, userInfoEndpoint) {
678
+ const response = await fetch(userInfoEndpoint, {
679
+ headers: {
680
+ Authorization: `Bearer ${accessToken}`,
681
+ Accept: "application/json"
682
+ }
683
+ });
684
+ if (!response.ok) {
685
+ throw new Error(`Failed to fetch user info: ${response.status} ${response.statusText}`);
686
+ }
687
+ const data = await response.json();
688
+ if (!data || typeof data !== "object" || !("email" in data) || typeof data.email !== "string") {
689
+ throw new Error(`Invalid user info response: missing or invalid email`);
690
+ }
691
+ return {
692
+ email: data.email,
693
+ id: "id" in data ? String(data.id) : void 0,
694
+ sub: "sub" in data ? String(data.sub) : void 0,
695
+ given_name: "given_name" in data ? String(data.given_name) : void 0,
696
+ family_name: "family_name" in data ? String(data.family_name) : void 0,
697
+ name: "name" in data ? String(data.name) : void 0,
698
+ picture: "picture" in data ? String(data.picture) : void 0,
699
+ email_verified: "email_verified" in data ? Boolean(data.email_verified) : void 0,
700
+ iss: "iss" in data ? String(data.iss) : void 0
701
+ };
702
+ }
703
+ async function extractUserInfo(tokenData, providerMetadata) {
704
+ let userInfo;
705
+ const userInfoEndpoint = providerMetadata.endpoints.userInfo;
706
+ if (tokenData.id_token) {
707
+ userInfo = decodeIdToken(tokenData.id_token);
708
+ } else if (tokenData.access_token) {
709
+ userInfo = await fetchUserInfo(tokenData.access_token, userInfoEndpoint);
710
+ } else {
711
+ throw new Error("No ID token or access token available to fetch user info");
712
+ }
713
+ return { userInfo };
714
+ }
715
+ // Annotate the CommonJS export names for ESM import in node:
716
+ 0 && (module.exports = {
717
+ Lixa,
718
+ decodeIdToken,
719
+ determineProviderFromIssuer,
720
+ extractUserInfo,
721
+ fetchUserInfo
722
+ });
723
+ //# sourceMappingURL=index.cjs.map