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